[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: lua_lock() and global lua variables
- From: Thijs Schreijer <thijs@...>
- Date: Mon, 7 Mar 2016 12:35:19 +0000
> -----Oorspronkelijk bericht-----
> Van: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org]
> Namens ???, Peng Yi
> Verzonden: Monday, 7 March, 2016 7:12
> Aan: lua-l@lists.lua.org
> Onderwerp: Re: lua_lock() and global lua variables
>
> 在 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.
>
Here's some more info I wrote for my own reference, might help understanding how it works;
http://www.thijsschreijer.nl/blog/?p=693
Thijs