我编写了以下简单的Lua程序,用POSIX threads in Lua测试条件变量:
local pthread = require 'pthread'
local cond = pthread.cond()
local mutex = pthread.mutex()
local ready = false
first = pthread.new(
function()
print('starting first')
mutex:lock()
print('first got lock')
while not ready do
cond:wait(mutex)
end
mutex:unlock()
print('first continuing')
end
)
second = pthread.new(
function()
print('starting second')
mutex:lock()
print('second got lock')
ready = true
cond:signal()
mutex:unlock()
print('second continuing')
end
)
first:join()
second:join()
mutex:free()
cond:free()
在Ubuntu Trusty的luajit 2.1.0-beta1下,这通常按预期运行,输出:
$ luajit condition.lua
starting first
first got lock
starting second
second got lock
second continuing
first continuing
然而,有时(经常)它会因为seg故障而崩溃。我做错了什么?