lua-users home
lua-l archive

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


It was thus said that the Great Gregg Reynolds once stated:
> On Dec 22, 2017 5:42 PM, "Sean Conner" <sean@conman.org> wrote:
> > 
> >   Getting back to Lua, Lua is based upon a VM, so it has its own concept of
> > RIP and RSP.  A call to lua_newstate() (or luaL_newstate()) returns a new
> > Lua VM context, which can be likened to a "process" in that it manages the
> > resources and contains at least one "unit of execution." The function
> > lua_newthread() creates a new "unit of execution" within the current Lua VM,
> > which the Lua documentation calls a "thread" but is more like a "coroutine"
> > although in any case, it's a "unit of execution" that needs to be
> > explicitely switched to.  And this "unit of execution" only has meaning to
> > the Lua VM---it is totally unrelated to the system notion of "units of
> > execution" (like threads or processes).
> > 
> >   -spc (Hope this helps some ... )
> 
> Definitely - well said! Something along these lines in PIL and/or the
> refman would be useful.
> 
> But now: what's the relationship between luathreads and platform threads?

  There is no relationship between the two.

> There is always only one lua vm, right? 

  There doesn't have to be:

	lua_State L1 = luaL_newstate();
	lua_State L2 = luaL_newstate();

  What happens in L1 does not affect L2 and vice versa.  They are
independent of each other.  

> In my use case, lua_newstate could
> be called simultaneously on multiple distinct platform threads. That would
> work so long as the Lua engine/vm is reentrant, yes?

  Lua is reentrant, but (by default) not thread safe.  That is, if a system
thread (pthread) calls into Lua with state L1, and another system thread
calls into Lua with state L1 at the same time, things blow up.  But system
thread 1 calling into Lua with state L1 and system thread 2 calling into Lua
with state L2 is fine.

  There is a way to compile Lua to make it thread safe, but 1) that means
you need to include your custom Lua library with your application and 2)
will slow Lua down to Python speeds.

> So my (wrapped, c) lib may call lua_newstate and then pass control to a
> user-defined Lua callback on multiple platform threads, in parallel. So
> long as the callback does not use (Lua) globals, everything should be
> copacetic, yes?

  Not if all the system threads use the same Lua state.

> What if the cb needs to read/write shared data? Do it by calling a C
> function that handles synchronization? Use coroutines in some way?

  Yes.

  -spc