gpt4 book ai didi

windows - lua lane 线程间通信

转载 作者:可可西里 更新时间:2023-11-01 11:21:12 27 4
gpt4 key购买 nike

有没有办法让 lua channel 线程进行通信或从外部访问线程?

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

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

这可以用 lua channel 吗?

我的意思是纯粹在 lua 中而不是在 c/c++ 中。

最佳答案

在使用多线程时,您通常 do not want to "update/change" a variable from multiple threads without any synchronization - 这可能会导致由于对变量/表等的不同步访问而导致随机出现的错误。

相反,您应该依靠消息传递来处理线程之间的通信。这称为 actor model并且直接受到某些语言的支持,例如 Erlang。

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

Without using busy loops...

虽然看起来像,但在 LuaLanes 中没有繁忙的循环。如果您尝试在没有值的键上 linda:receive(),LuaLanes puts the reading thread on a wait直到 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

关于windows - lua lane 线程间通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9572317/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com