lua-users home
lua-l archive

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


> 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 ;-)


On Mon, Aug 24, 2020 at 10:04 PM Viacheslav Usov <via.usov@gmail.com> wrote:
On Mon, Aug 24, 2020 at 8:46 PM bel <bel2125@gmail.com> wrote:

> What would be the appropriate way to implement a "luaclose_mylib" function in C, that would work as an inverse of "luaopen_mylib"?

Have you considered that your library might be used by a process with
multiple Lua states, which come and go dynamically in parallel
threads?

My advice is NOT to have any global state in a library. Instead, all
the state should be linked to the object that the require function
returns. Doing otherwise is a source of persistent problems,
especially in the scenario above.

Cheers,
V.