lua-users home
lua-l archive

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


Johann Hibschman wrote:
Rici Lake wrote:
The coroutine mechanism is not implemented with threads, although the API calls them threads (which they are, but not OS threads); Lua threads are exposed as instances of a Lua_State, and those Lua_States are related to each other. You probably don't want to run those simultaneously in different OS threads, but it is theoretically possible; the language does not provide any synchronization primitives, though, so you need to implement your own so that related Lua_States don't trod on each other's globals.

I keep wondering about this; wouldn't the garbage collector require some synchronization, in order to avoid trouble with multiple Lua-threads running in multiple OS-threads?

Yes, and Lua does that (if you configure it to).

There are macros lua_lock() and lua_unlock() which are supposed to acquire and release a mutex (or something equivalent). Lua ensures
that the mutex is held during the execution of any Lua API function,
and during the execution of the Lua VM. While the VM is running, the
lock is periodically released in order to allow other related states
to run. During a garbage collection action, the lock is held.

It's not really very good if you have a bunch of Lua functions
running simultaneously in multiple OS threads. It works OK if
the threads are usually not executing Lua functions. Otherwise,
you're really better off using separate Lua states, which don't
require any synchronization.

Regardless, the synchronization only protects internal Lua
structures. The statement  'a = a + 1' does not have
well-defined semantics if 'a' is accessible from more than
one simultaneously active (related) Lua state.