簡體   English   中英

Lua-線程化

[英]Lua - Threading

在下面的代碼中,我從設備讀取值,在其中添加時間戳,然后通過電子郵件發送字符串。 函數“ 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

存在很多線程庫(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

使用此代碼,您還可以將消息排隊。 但是,如果生成消息的速度比發送消息的速度快,那么最終將導致應用程序崩潰而沒有內存錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM