0

我正在尝试在 2 个 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


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

从上面的代码实现锁有什么问题吗?

4

1 回答 1

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()
于 2013-10-07T18:32:22.603 回答