lua-users home
lua-l archive

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


在 2016/2/28 19:23, Vyacheslav Napadovsky 写道:
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);
}


You've done it incorrectly. what `lua_newthread` returns is what is called a coroutine in Lua.
sometimes also called cooperative multi-threads, or green threads. it is essentially an abstraction
of an yield-able and resume-able execution flow, you are not supposed to use it from a separate
underlying OS thread, which is preamble.


if you really need multiple OS threads, consider a different approach: every thread get its own Lua universe,
and use explicit communication between different Lua states. just like how Lualanes does it.

--
the nerdy Peng / 书呆彭 / Sent from Thunderbird