【问题标题】:Lua - ThreadingLua - 线程
【发布时间】:2015-06-04 21:23:14
【问题描述】:

在以下代码中,我从设备读取值,为其添加时间戳并通过电子邮件发送字符串。函数“send_email()”需要 3 分钟并停止其余代码的工作。 所以我的目标是在另一个线程或类似线程上执行函数“send_email()”,这样收集的数据集之间就没有 3 分钟的间隔。因为此时不会收到新数据,但我需要收集所有数据。

It should give out:   value_10:30:00 -> value_10:30:10 -> value_10:30:20...
not:                  value_10:30:00 -> value_10:33:10 -> value_10:36:20...

请注意,以下代码是伪代码。

function main()

    time     = get_time()  --prints the clocktime (format: hour, minutes, seconds)
    mystring = read_value_from_device()
    mystring = mystring .. "_" .. time

    send_email(mystring) --send email (this takes up to 3 minutes!)

    sleep(10)    --sleeps 10 seconds

    main()       --call function again
end

【问题讨论】:

  • 没有线程,但是可以使用类似的协程。
  • Thx,我昨天已经告诉过我有关协程的信息,但我不知道如何在我的代码中使用它。感谢您的帮助。
  • 另一个想法是使用命令“dofile”来执行发送电子邮件的外部文件,但是否可以将变量(mystring)移交给该函数,以便它知道要做什么发送?
  • 阅读有关协程的 Lua 手册。很清楚。
  • 如果这么清楚,那我就不用在这里问了。

标签: multithreading lua coroutine


【解决方案1】:

存在许多线程库(LuaLanes,lua-llthreads) 我使用我的 lua-llthreads2/lua-lzmq

local zthreads = require "lzmq.threads"

-- Create separate OS thread with new Lua state
local thread = zthreads.xactor(function(pipe)
  -----------------------------------------------------
  -- !!! DO NOT USE UPVALUES FROM MAIN LUA STATE !!! --
  -----------------------------------------------------
  while true do
    -- use pipe to get next message
    local msg = pipe:recv()
    if not msg then break end
    print("Thread code:", msg)
  end
end):start()

for i = 1, 10 do
  -- send new message to thread
  thread:send("Message #" .. i)
end

使用此代码,您还拥有消息队列。 但是,如果您生成消息的速度比发送消息的速度快,那么您最终会导致应用程序崩溃而没有内存错误。

【讨论】:

    猜你喜欢
    • 2017-08-23
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2014-08-12
    • 2014-01-29
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多