windows - lua lane 线程间通信

标签 windows linux multithreading lua

有没有办法让 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/

相关文章:

linux - 为单词列表中的每个单词创建一个包含匹配项的文件

java - 我的 JDialog 有时会收到来自调用应用程序的多余按键? (提供代码)

Windows 批处理文件启动带有按钮的 gui

c++ - 获取一个txt文件的内容

linux - BASH - 比较两个文件并将输出重定向到可读的内容

linux - Ubuntu Linux 中的异步 IO io_submit 延迟

java - SwingWorker 中的 thread.sleep()

java - 为什么另一个线程在同步部分尚未完成时可以访问阻塞对象?

windows - 在外部程序执行时捕获它的 STDOUT 和 STDERR (Ruby)

游戏中的java.awt.Robot?