【问题标题】:Lock between Lua lanes在 Lua 通道之间锁定
【发布时间】:2013-10-05 15:43:35
【问题描述】:

我正在尝试在 2 个 Lua 通道之间使用锁,但观察到两个通道同时进入 lock_func ..下面是 sn-p

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

从上面的代码实现锁有没有问题?

【问题讨论】:

  • 我对 Lanes 了解不多,但是为什么要覆盖 'lock_func' 变量呢?你只是扔掉'lanes.genlock'调用的结果。
  • @peterm ..感谢您的输入。我已经在下面发布了答案,但没有覆盖 lock_func。关于如何正确使用锁,车道文档让我有点困惑..

标签: lua lua-lanes


【解决方案1】:

lua 中锁的实现可以通过下面的代码 sn-p 来完成。下面的代码只会执行来自写入器或读取器通道的打印,因为获得锁的通道将进入无限循环(只是为了看到锁按预期工作),其他通道将等待锁被释放.

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-03
    • 2016-06-28
    • 2021-12-11
    • 1970-01-01
    • 2023-01-11
    • 2018-05-13
    • 2010-10-27
    • 1970-01-01
    相关资源
    最近更新 更多