Creating a single lua_State
per thread is a good solution to having multiple threads of Lua execution. However, those states are very separated. In particular, it is difficult to safely communicate between them since the Lua API is only thread-safe as long as each lua_State
is accessed from a single thread at a time. (Well, unless lua_lock
and lua_unlock
are implemented as a suitable mutex, which they are not in the default builds of the lua core.)
If that level of isolation is not acceptable, then you need to investigate one of the several mechanisms for allowing Lua instances to play well with others in a threaded process.
My favorite choice is Lua Lanes which provides for multiple threads along with a mechanism for passing messages and sharing values between them in a thread-safe way. Values of most Lua types (including userdata
with a little C side support from the library that uses it) can be safely and efficiently passed from one lane to another.
Other mechanisms exist, and a good starting point for most of them is at the Lua user's wiki page on MultiTaksing.