Lua - Threading

风流意气都作罢 提交于 2019-12-08 11:04:28

问题


In the following code i read values from a device, add a timestamp to it and send the string via e-mail. The function "send_email()" needs 3 minutes and stops the rest of the code from working. So my aim is to execute the function "send_email()" on another thread or similar, so that there is no gap of 3 minutes between the collected datasets. Because in this time no new data will be received, but i need to collect all data.

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...

Note that the following code is pseudo code.

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

回答1:


There exists many threads library (LuaLanes, lua-llthreads) I use my 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

With this code you also have queue of your messages. But if you will generate messages faster than send them out you end up with application crash with no memory error.



来源:https://stackoverflow.com/questions/29370311/lua-threading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!