我想在2个通道之间共享一个全局变量,这个想法是当lane1更新共享变量时,我应该能够在它被调度时获得它在lane2上的更新值。有解决方案吗?
以下代码段: -
shared_variable = 0
local function lane1()
..
shared_variable = shared_variable + 1
end
local function lane2()
..
print(shared_variable)-->shared variable is not getting updated,always prints 0
end
Thread1= lanes.gen("*",{globals = _G},lane1)
Thread2= lanes.gen("*",{globals = _G},lane2)
T1 = Thread1()
T2 = Thread2()
T1:join()
T2:join()
答案 0 :(得分:2)
下面是我们可以在Lines之间共享变量的示例实现(使用set和; get方法)
require("lanes")
shared_variable = 0
local linda = lanes.linda()
local function lane1()
while true do
shared_variable = shared_variable + 1
linda:set("var", shared_variable)
end
end
local function lane2()
while true do
local v = linda:get("var")
print(v)
end
end
Thread1= lanes.gen("*",{globals = _G},lane1)
Thread2= lanes.gen("*",{globals = _G},lane2)
T1 = Thread1()
T2 = Thread2()
T1:join()
T2:join()
答案 1 :(得分:1)
你必须使用lindas自己同步变量 - 这是文档:
http://kotisivu.dnainternet.net/askok/bin/lanes/#lindas
这是您的代码的固定版本:
require("lanes")
shared_variable = 0
local linda = lanes.linda()
local function lane1()
while true do
shared_variable = shared_variable + 1
linda:send("var", shared_variable)
end
end
local function lane2()
while true do
local v = linda:receive("var")
print(v)
end
end
Thread1= lanes.gen("*",{globals = _G},lane1)
Thread2= lanes.gen("*",{globals = _G},lane2)
T1 = Thread1()
T2 = Thread2()
T1:join()
T2:join()