lua-users home
lua-l archive

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


On 28.08.2016 11:57, Marc Balmer wrote:
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?


Our system has a similar scenario. We use a message driven approach to solve multi-threading problems like this. Instead of using locks over the Lua state, the Lua state 'belongs' strictly to the main thread. If another thread want's to access the Lua state, it passes a message to the main thread, which executes the Lua function and passes the results back to the calling thread.

Now, as it has been said, it is important to know whether you need preemptive scheduling or not. If you don't need preemptive scheduling you can simply make a main loop in you main thread that does nothing else but waiting for work to do.
--

Thomas