简体   繁体   中英

Lua - Threading

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM