Lua Lanes 线程间通信

lua lanes 线程是否有一种方式进行通信或从外部访问这些线程?

不使用文档提供的忙碌循环。

一个简单的例子是,一个线程使用一个变量,更新它,改变它等等,而另一个线程或主程序能够访问/获取该变量。

Lua lanes 是否支持这种方式?

我指的纯粹是在 lua 中而不是来自 c/c++。

原文链接 https://stackoverflow.com/questions/9572317

点赞
stackoverflow用户221509
stackoverflow用户221509

使用多线程时,通常不应该在没有任何同步的情况下从多个线程中"更新/改变"变量,否则,这可能会导致由于对变量/表等未同步访问而导致的随机出现的错误。相反,应该依赖于消息传递来处理线程之间的通信。这称为actor model,某些语言(如Erlang)直接支持它。

LuaLanes也采用了这种通信模式。要在各个通道之间通信,需要创建一个Linda对象,该对象可以由主线程和孵化线程共享,并用于通信。 Linda对象为您处理同步,不需要您进行锁定。每个操作(发送、接收消息)都是原子的。

不使用繁忙的循环...

尽管可能看起来像,但LuaLanes中没有忙等待的循环。如果您尝试使用没有值的密钥进行linda:receive(),LuaLanes则将读取线程置于等待状态,直到修改linda对象。因此,线程处理消息的一般方式如下:

local lanes = require "lanes"
local linda = lanes.linda()
local thread = lanes.gen("*", function()
    print("Starting thread...")
    while true do
        local command = linda:receive("cmd")
        if command=="quit" then
            break
        else
            -- do processing based on command
        end
    end
end)

local threads = {}
local NCORES = 4
for i=1,NCORES do threads[i] = thread() end     -- start the threads
-- send messages, like files for processing, using linda:send("cmd", {file=..., op=...})
for i=1,NCORES do linda:send("cmd", "quit") end -- send the quit command
for i=1,NCORES do threads[i]:join() end         -- wait for the threads to end
2012-03-05 19:56:20