tags:

views:

76

answers:

1

What is the point of lua_lock and lua_unlock?

The following implies it's important:

LUA_API void lua_gettable (lua_State *L, int idx) {
  StkId t;
  lua_lock(L);
  t = index2adr(L, idx);
  api_checkvalidindex(L, t);
  luaV_gettable(L, t, L->top - 1, L->top - 1);
  lua_unlock(L);
}


LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
  StkId t;
  TValue key;
  lua_lock(L);
  t = index2adr(L, idx);
  api_checkvalidindex(L, t);
  setsvalue(L, &key, luaS_new(L, k));
  luaV_gettable(L, t, &key, L->top);
  api_incr_top(L);
  lua_unlock(L);
}

The following implies it does nothing:

#define lua_lock(L)     ((void) 0) 
#define lua_unlock(L)   ((void) 0)

Please enlighten.

+6  A: 

If you port Lua to another platform, you are "allowed" to overwrite lua_lock with your own definition; and this definition should essentially be a mutex, to disallow cross-thread operations on the same Lua objects. Essentially, when implemented, it should act similarly to Python's Global Interpreter Lock (GIL).

It's defined to a no-op in vanilla Lua, because vanilla Lua is 100% ANSI-C and runs in a single thread: there's no need for any locking mechanism to be implemented. However, the developers chose to put the lock statements in there for people who port Lua and implement threading in the interpreter.

Sources:

Mark Rushakoff
If this needs to be mutex-protected on other archs, why is it not necessary on 64-bit ubuntu on x86? [the system I'm running on]
anon
If you allow the Lua API to be called for the same `lua_State` from multiple threads, then you *must* define an appropriate `lua_lock` and `lua_unlock`. The default build does not do this because it hurts performance for the most common single-thread case, so you cannot use a single `lua_State` from multiple threads.
RBerteig