lua-users home
lua-l archive

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


2016-08-28 10:57 GMT+01:00 Marc Balmer <marc@msys.ch>:
> Does someone on this list have experience with running Lua in a threaded environment?
>
> I am thinking about the following scenario:
>
> - A main thread creates a Lua state and uses it the usual way using the C API.
> - A secondary thread should call a function in said Lua state from time to time,
> asynchronously and not predictable when it will do so. Totally independent from
> the main thread.
>
> It's obvious that this will not work and that some sort of arbitration will be needed.  As
> I understand, there is no locking at all in Lua, and not even a function to query if a
> Lua state is currently executing Lua code, i.e. if another thread is running the Lua
> interpreter.
>
> What's the best approach to this?  I think I will have to add a locking mechanism
> and aquire the lock before calling any of the Lua C API functions.  Are there better
> ways?

As suggested by Daurnimator using lua_lock/lua_unlock is the way to go
(IMHO, assuming you can recompile Lua). However keep in mind that the
more code you run in Lua, the more delays will be introduced before
your asynchronous code is executed. In the worst (degenerate) case,
where the main thread only runs Lua code 100% of the time (think
"while true do end") then your asynchronous code will *never* be
executed.

If you really need preemption, then I think you should look at how
signal handling is done in the stock interpreter. It installs a one
time hook on call, return and count=1. I'm not sure how thread safe
that is, I can only guess it's safe enough to call from a signal
handler if the stock interpreter does it. But does that translate to
the kind of preemption you want to use?