lua-users home
lua-l archive

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

On 2-Feb-06, at 8:24 PM, Chris wrote:

On 2/2/06, Rici Lake <> wrote:

You cannot randomly access a Lua state's stack while that Lua state is
actively running a script.
Yes, I think that answers my question.  You simply can not access a Lua state from another thread, even with the internal locking enabled.

 Is a shame.  :(

Well, without knowing what exactly you're trying to do, it's hard to offer much in the way of advice, but there is certainly nothing stopping you from setting up a single Lua state ("universe") and using multiple Lua threads, each in their own native thread (or not). In that case, you would only have a single state and a single mutex, and the various threads could (cautiously) share data.

I personally wouldn't use that strategy, for a number of reasons:

1) The lua_lock() mechanism only protects the integrity of Lua data structures. It does not protect the integrity of data held in Lua tables, for example, in the sense that it does not provide any sort of atomic update. That is, unless you provide your own locking mechanism, you cannot guarantee that the following is atomic:

  lua_Number x;
  lua_getglobal(L, "foo");
  x = lua_tonumber(L, -1);
  lua_pushnumber(L, x + 1);
  lua_setglobal(L, "foo");

The global "foo" could be modified by another thread at any point in that process.

2) Unnecessary lock contention is fairly likely if you're running a number of threads in an SMP environment. Most of the time, the various threads are probably not using shared resources.

3) The frequent calls to lua_lock() and lua_unlock() slow things down a bit.

On the other hand, there is nothing stopping you from creating a binding to an arbitrary shared structure, which the various threads could access through a userdata. That structure would need its own lock, of course. You could make that look really a lot like the userdata were a native table. So that way you could run multiple Lua universes without the lua_lock() mechanism, as long as you ensured that each Lua universe was only active in one thread (at a time).