3.20 – Threads
Lua offers partial support for multiple threads of execution. If you have a C library that offers multi-threading, then Lua can cooperate with it to implement the equivalent facility in Lua. Also, Lua implements its own coroutine system on top of threads. The following function creates a new thread in Lua:
- lua_State *lua_newthread (lua_State *L);
This function pushes the thread on the stack and returns a pointer to a lua_State
that represents this new thread. The new state returned by this function shares with the original state all global objects (such as tables), but has an independent run-time stack.
Each thread has an independent global environment table. When you create a thread, this table is the same as that of the given state, but you can change each one independently.
There is no explicit function to close or to destroy a thread. Threads are subject to garbage collection, like any Lua object.
To manipulate threads as coroutines, Lua offers the following functions:
- int lua_resume (lua_State *L, int narg);
- int lua_yield (lua_State *L, int nresults);
To start a coroutine, you first create a new thread; then you push on its stack the body function plus any eventual arguments; then you call lua_resume
, with narg
being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, the stack contains all values passed to lua_yield
, or all values returned by the body function. lua_resume
returns 0 if there are no errors running the coroutine, or an error code (see 3.15). In case of errors, the stack contains only the error message. To restart a coroutine, you put on its stack only the values to be passed as results from yield
, and then call lua_resume
.
The lua_yield
function can only be called as the return expression of a C function, as follows:
- return lua_yield (L, nresults);
When a C function calls lua_yield
in that way, the running coroutine suspends its execution, and the call to lua_resume
that started this coroutine returns. The parameter nresults
is the number of values from the stack that are passed as results to lua_resume
.
To exchange values between different threads, you may use lua_xmove
:
- void lua_xmove (lua_State *from, lua_State *to, int n);
It pops n
values from the stack from
, and puhses them into the stack to
.