Black
Black

Reputation: 20212

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

Upvotes: 0

Views: 1117

Answers (1)

moteus
moteus

Reputation: 2235

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.

Upvotes: 1

Related Questions