Lua-线程化 [英] Lua - Threading

查看:126
本文介绍了Lua-线程化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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.

这篇关于Lua-线程化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆