lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


于 2012-3-27 17:49, steve donovan 写道:
Hi all,

I've been recently trying to get winapi to do Real Things, and I'm
hitting those little random crashes which suggest that multithreading
in Lua is not as simple as I naively thought.

Current design is e.g. to have a thread waiting for i/o, and then
dispatch the callback when a read() returns, ensuring that only one
callback can be active at a time using mutexes.  (Ditto for timers and
so forth).  One obvious problem is that we could be running Lua code
in the main thread anyway, which suggests that the mutex should only
unlocked when we are sleeping or otherwise waiting on some event.  But
the callbacks still happen on _another thread_, so I wonder if this
isn't the real problem.

Can such a design be made truly solid? I remember reading that Mike
Pall reckoned that coroutines created from the C side should work
fine.

(My apologies for the vagueness, but multithreading is not my native language)

steve d.


As far as I know, the only safe way in Lua to fire asynchronous events is to set a debug hook in the asynchronous callback and
wait the Lua VM call the debug hook at some safe time (i.e. at VM instruction boundaries, to ensure the consistent of the Lua state)..
and you may do your work in the hook. because I found only `lua_sethook' can be called asynchronously.

the standalone interpreter use the debug hook to handle SIGINT, allow users to interrupt the VM by pressing CTRL-C.
you may refer to lua.c for details.

And, I see the lua_unlock and lua_lock macro in luaconf.h, which I guess may be defined by user to handle concurrent problems,
but they are not documented, and I have not carefully checked them in the source code, so I'm not sure how to use them.