我正在尝试使用两个Lua通道之间的锁,但发现这两个通道同时进入了lock_func ..Below是片段
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
从上面的代码执行锁定有什么问题吗?
答案 0 :(得分:0)
lua中锁的实现可以在下面的代码片段中完成。只有来自编写器或读取器通道的打印才能从下面的代码执行,因为获取锁的任何通道都将进入无限循环(只是为了看到锁正在按预期工作)&其他车道将等待锁定被释放。
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()