Reputation: 185
Is there a way to for lua lanes threads to communicate or to access the threads from outside of it?
Without using busy loops like the documentation provides.
A simple example would be, a threads using a variable, updating it, changing it etc and another thread or the main program to be able to access/get that variable.
Is this possible with lua lanes?
And I mean purely in lua not from c/c++.
Upvotes: 1
Views: 2255
Reputation: 16753
While using multiple threads, you usually do not want to "update/change" a variable from multiple threads without any synchronization - this could lead to randomly appearing errors caused by unsynchronized access to variables/tables, etc.
Instead, you should rely on message passing to handle communication between threads. This is called the actor model and is directly supported by some languages, like Erlang.
LuaLanes also embraces this model of communication. To communicate between various lanes, you create a Linda object, which can be shared by the main thread and spawned threads, and used to communicate. Linda objects handle synchronization for you, no locking from your side is required. Every operation (sending, receiving a message) is atomic.
Without using busy loops...
Although it may seem like it, there are no busy loops in LuaLanes. If you try to linda:receive()
on a key with no value, LuaLanes puts the reading thread on a wait until the linda object is modified. So the general way for a thread to handle the messages is as follows:
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
Upvotes: 4