luajit/physicsfs 互斥锁死锁问题

我有以下代码:

local M=ffi.load "physfs"
ffi.cdef [[ //basically the preprocessed content of physfs.h, see http://icculus.org/physfs/docs/html/physfs_8h.html ]]
M.PHYSFS_init(arg[0])
M.PHYSFS_setSaneConfig("a","b","zip",0,0)

function file2str(path)
  local cpath=ffi.cast("const char *",path)
  print(1) --debug
  if M.PHYSFS_exists(cpath)==0 then return nil,"file not found" end
  print(2) --debug
  -- some more magic
end
assert(file2str("someFile.txt"))

在调用时,我期望得到调试输出1和2,或者至少触发断言,但我只得到:

1
["endless" (i pressed ^C after about a minute) freeze]

当最终让 luajit 在 gdb 中运行时,冻结时的回溯如下:

(gdb) bt
#0  0x00007ffff37a5c40 in __pause_nocancel ()
    at ../sysdeps/unix/syscall-template.S:81
#1  0x00007ffff379bce6 in __pthread_mutex_lock_full (mutex=0x68cbf0)
    at ../nptl/pthread_mutex_lock.c:354
#2  0x00007ffff606951f in __PHYSFS_platformGrabMutex (mutex=0x68cbf0)
    at /home/kyra/YDist/src/physfs-2.0.3/platform/unix.c:403
#3  0x00007ffff606410d in PHYSFS_getWriteDir ()
    at /home/kyra/YDist/src/physfs-2.0.3/physfs.c:913
#4  0x000000000045482b in ?? ()
#5  0x000000000043a829 in ?? ()
#6  0x000000000043af17 in ?? ()
#7  0x00000000004526a6 in ?? ()
#8  0x0000000000446fb0 in lua_pcall ()
#9  0x00000000004047dc in _start ()

所以对我来说,似乎有些东西阻止了互斥锁,这有点奇怪,因为虽然有两个线程在运行,但只有一个线程甚至触及 physfs(第二个线程甚至没有 'ffi.load "physfs"')

我应该怎么做?

点赞
用户668125
用户668125

我仍然不知道到底发生了什么,但在尝试在gdb中进一步调试互斥锁时,我将libpthread.so预加载到gdb进程中,然后它突然可以工作了。

之后,我尝试将其预加载到没有gdb的luajit中,也能正常工作。

然后我进一步研究了physfs和lualanes(这是我用于线程的pthread ffi包装器),发现如果尚未加载,则两者都尝试加载libpthread,但是physfs是从C语言,而lualanes则使用ffi加载,其某种方式无法看到由physfs加载的版本,进程最终会加载两个库的副本。

因此,解决方法是在ffi.load“physfs”之前显式执行ffi.load“pthread”,因为虽然lanes看不到由physfs加载的版本,但physfs只能使用我们加载的版本,不会再次尝试加载它,而luajit ffi会忽略lanes进行的进一步加载尝试。

2015-02-13 22:03:27