> Have you considered that your library might be used by a process with
> multiple Lua states, which come and go dynamically in parallel
> threads?
I *know* my library is used in exactly this way.
Even worse: The Lua states may communicate with each other (which is a topic in itself), and all must be "strictly sandboxed" so they don't harm the execution environment and influence each other as little as possible.
Yet, there are restrictions in the backend (the library used by my library) that do require one global state.
So the solution must look something like:
luaopen_mylib(lua_State * L)
{
mutex_lock();
if (refcount == 0) {
my_global_open(); // <-- heavy weight operation
}
refcount++;
mutex_unlock();
init_lua_state_specific_stuff() // <-- can be stored in L
lua_new..stuff(L); (luaL_requiref or whatever)
}
luaclose_mylib(L)
{
mutex_lock();
refcount--;
if (refcount == 0) {
my_global_close(); // <-- this is the essential operation here
}
mutex_unlock();
free_lua_state_specific_stuff(L);
}
and some library functions require locks too, or serialization through message queues.
(Yes, it's a full scale distributed multithreaded system with many manyears on code that is supposed to run unattended for months/years ... I think I know *exactly* what kind of problems you have in mind ...)
A bug in reference counting may either cause a memory leak, or a complete crash by calling into an unloaded module.
--> This is why I'm asking here.
And yes, of course I will test it extensively ;-)