InMultithreadingUsed inLuaThe method is the content to be introduced in this article, as you know, until now lua 5.1,LuaThe functions in are not provided with thread-safe implementation. So ifMultithreadingWhen you access lua_State in, unexpected results are generated. However, the current application software generally requiresMultithreadingTo meet the application requirements.
If you cannotMultithreadingUsed inLuaThis will be a huge limit for Lua. But is there any way to solve this problem? Fortunately, lua provides multi-threaded functions to solve the problem of multithreading. The five function prototypes are as follows:
- int lua_newthred(lua_State* L)
- int lua_resume(lua_State* L, int nargs)
- int lua_yield(lua_State* L int nresults)
- void lua_lock(lua_State* L)
- void lua_unlock(lua_State* L)
We use the above five functions, coupled with thread synchronization. Basically, it can solve the application problem of Lua in multithreading. For detailed usage of the above five functions, see the lua Development Guide. In the following example, the corresponding code is provided for your reference.
1. a Lua stack error occurs when multiple threads are used,
Cause of the problem: using the same lua_State in multiple threads can lead to errors in the lua stack.
Solution: Use the lua_newthread function to generate a new stack to prevent stack access conflicts.
Solution code example: in actual use, you need to maintain lua stack access conflicts with caution. When you call lua_newthread, you also need to synchronize the mechanism to protect it. You need to implement lua_lock and lua_unlock, to ensure that multi-threaded access does not conflict. ):
- lua_State* L = lua_newthread(luaMain)
- ...
- lua_pushstring(L, str);
- ...
- lua_resume(L, n)
2. Pause the execution of the Lua script, but prevent the main thread of the Host Program from getting stuck.
Solution: You can call the lua_yield function in the Host Program to pause script execution. When the host program completes the execution task, call lua_resume to resume the execution of the lua script.
The sample code is as follows:
- C ++:
- Int show_dialog (void)
- {
- ....
- Lua_pushnumber (L, IDOK );
- Return lua_yield (L, n); The \ lua_yield function must be placed behind the return statement.
- }
- Int end_dialog (void)
- {
- ...
- Int ret = lua_resume (L, 0 );
- If (ret = LUA_YIELD)
- {
- Int id = lua_tonumber (L,-1 );
- }
- Return 2;
- }
- Lua:
- Ret = show_dialog ()
- If ret = 0 then
- End
Summary:MultithreadingUsed inLuaThe content of this method has been introduced. I hope this article will help you!