lua-users home
lua-l archive

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


On 21-Jul-04, at 5:39 PM, Johann Hibschman wrote:

Is there any reference on how to use Lua in a heavily-threaded application, with some usage of shared state? I'd expect the game folks do this all the time, but I couldn't find any good examples.

I'll be interested in seeing replies to this.

I'm a little worried that the GC would interfere with things, if the "run a thread" code were called while the main thread were GCing.

Lua locks all threads while garbage collecting (and indeed while modifying any internal structure) so there is no chance of interference. However, it does mean that GC will block all threads.

The giant interpreter lock does guarantee that the Lua internal structures will remain coherent. But it does not at all guarantee that individual threads will have a consistent view of the world, if they share state with each other.

For example the simple statement:

  a = a + 1

where a is a global variable could generate unpredictable results. And Lua does not provide any interpreter-visible synchronization primitives which would let you prevent that. Of course, the problem could be avoided by giving each thread its own globals environment, but then one has to wonder what the point of using Lua threads was.

In fact, even lauxlib's luaL_ref() system is vulnerable to threading issues, because the Lua environment is not locked while luaL_ref is updating the linked free list.

Given all that, my inclination in threading Lua is not to; that is, to keep a separate Lua instance for each thread and to do inter-thread communication (if necessary) through a separate library.