Lua车道之间的锁定
我试图在两个Lua通道之间使用锁,但观察到两个通道同时进入lock_func.。下面是代码片段Lua车道之间的锁定,lua,lua-lanes,Lua,Lua Lanes,我试图在两个Lua通道之间使用锁,但观察到两个通道同时进入lock_func.。下面是代码片段 Code Snippet ================== require"lanes" local linda = lanes.linda() lock_func = lanes.genlock(linda,"M",1) local function lock_func() print("Lock Acquired") while(true) do end end
Code Snippet
==================
require"lanes"
local linda = lanes.linda()
lock_func = lanes.genlock(linda,"M",1)
local function lock_func()
print("Lock Acquired")
while(true) do
end
end
local function readerThread()
print("readerThread acquiring lock")
lock_func()
end
local function writerThread()
print("writerThread acquiring lock")
lock_func()
end
Thread1= lanes.gen("*",{globals = _G},writerThread)
Thread2= lanes.gen("*",{globals = _G},readerThread)
T1 = Thread1()
T2 = Thread2()
T1:join()
T2:join()
从下面的输出中,我们可以看到两条车道同时进入lock_func功能
output
==================
writerThread acquiring lock
Lock Acquired
readerThread acquiring lock
Lock Acquired
上面代码中的锁的实现是否有任何问题?在lua中实现锁可以按照下面的代码片段进行。从下面的代码中只执行来自writer或reader通道的打印,因为获取锁的任何通道都将进入无限循环(只是为了看到锁按预期工作),其他通道将等待锁释放
require"lanes"
local linda = lanes.linda()
f = lanes.genlock(linda,"M",1)
local function readerThread()
require"lanes"
f(1)
print("readerThread acquiring lock")
while(true) do
end
f(-1)
end
local function writerThread()
require"lanes"
f(1)
print("writerThread acquiring lock")
while(true) do
end
f(-1)
end
Thread1= lanes.gen("*",{globals = _G},writerThread)
Thread2= lanes.gen("*",{globals = _G},readerThread)
T1 = Thread1()
T2 = Thread2()
T1:join()
T2:join()
我对Lanes了解不多,但为什么要覆盖“lock_func”变量?您只需扔掉“lanes.genlock”调用的结果。@peterm..谢谢您的输入。我已经在下面发布了答案,但没有覆盖锁函数。关于如何正确使用锁,lanes文档让我有点困惑。。