lua-users home
lua-l archive

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


Hello everyone.

I've reading through the OS-threading material, and there is a thing I
do not quite understand. It seems a lua_state L can be accesed by
different threads if I correctly define lua_lock(L)/lua_unlock(L).

We are currently using the lua_state wrapped in a C++ class which only
lets us enter a state when locked by a mutex, and using
coroutines/events without problems. We normally do not need to execute
anything multithreaded as we dispatch lengthy operations to a thread
pool which fires the result backs (locking).

But I could make some code much simpler if I could unlock the
interpreter while performing some calls from C functions. Reading
about lua_lock/unlock and wandering through the source, ldo.c , I've
found that C function calls are performed unlocked by them. So I
wonder if the following is safe:

1.- I enter the interpreter lock it and start executing lua code.
2.- Lua code calls one of my C functions.
3.- The C function then unlocks the interpreter....
4.- does some operation NOT touching it....
5.- relocks the interpreter, waiting if needed....
6.- and returns to lua code...
7.- which exits the interpreter and unlocks it.

Meanwhile, after 3 and before 5 some other threads may want to fire an
event, which implies locking, executing some lua code until exits and
unlocking.

Is this safe to do? I'm not worried about deadlocks ( there cannot be,
step 4 is fully independent, like a sleep ) or wait time ( it has an
appropiate time limit ) , or failing to return in 4 ( it's a fatal
error and needs program abort ), and I do not need fully interleaved
execution ( all the potential events are fast, and step 5 can wait
without problems ).

I'm currently doing this using coroutines, sending the execution to a
thread pools and yielding and having the thread pool resume the
coroutine with the result, which makes the scaffolding code dwarf the
real calling code, and I want a simpler solution.

Francisco Olarte.