Question
I'm working with in LUA's thread and I'm using lua_newthread for this in my code must perform the same function n times.
To work with the competition's thread instantiate some threads in C + + and for each thread assigns a lua_state this lua_state = lua_newthread. This thread's are destroyed only at the end of the application, so I'm always reuse the attribute lua_state these thread's. My question is this, after some run time, a crash happens in the application, this can be caused by the garbage collector?
In my last application I used the command lua_gc (thread, LUA_GCSTOP, 0), and yet the error persisted.
Another strategy I tried was the end of each run of lua_resume, I added the command lua_settop (thread, 0), so that the battery was drained and did not consume any memory space.
Please help me, what can happen?
Solution
Lua threads are not like CPU-threads. Lua is not thread-safe; you cannot execute Lua code in parallel across actual threads. Lua allows for cooperative multitasking, but not real CPU-threads.
You can call into different actual lua_State
objects from different CPU-threads, but only if they are truly separate. If you created a Lua thread from a root lua_State
, then you cannot call Lua code on that Lua thread while also calling Lua code on the root lua_State
. If two Lua threads share the same parent lua_State
, you cannot be executing Lua code on both of these Lua threads at the same time.
So you need to restructure what you're doing. Instead of using a thread, use lua_newstate
to create one Lua state for each CPU thread. Each lua_State
will be completely independent of the rest.