lua-users home
lua-l archive

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


Hello.

I'm trying to understand Lua 5.1 multi-threading support.

I understand that lua_lock and lua_unlock macroses is intended to prevent concurrent access to lua_State, but what about Lua _G table?

I think one mutex per one lua_State* (created with lua_newthread or luaL_newstate) is enough. And if so, then how Lua _G table will be shared among 2 system threads calling lua_pcall?

I mean, how lua_lock & lua_unlock usually implemented to make the C++ code below run correctly? (output will contain 10000 values between 0..10000 in ascending order with duplicates, but lua_States from different system threads will access correctly to _G.tbl.value) And does redefinition of lua_lock & lua_unlock is enough to make Lua multithreaded?

void threadfunc(lua_State* L) {
    lua_pushstring("threadfunc");
    lua_pcall(L, 1, 0);
}

void main() {
    lua_State *global = luaL_newstate();
    luaL_openlibs(global);
    // loading some script with "require" call
    /* script code:
       tbl = { value = 0 };
       function threadfunc()
           for i=1,10000 do
               tbl.value = i
           end
       end
       function mainfunc()
           for i=1,10000 do
               print(tbl.value);
           end
       end
    */
    lua_State* luathread = lua_newthread(global);
    std::thread thread(&threadfunc, luathread);
    lua_pushstring("mainfunc");
    lua_pcall(L, 1, 0);
    thread.join();
    lua_close(global);
}

--
Vyacheslav Napadovsky