Search code examples
c++multithreadingdlopen

dlopen/dlclose execution environment


I have a Linux process within multiple threads that uses dlopen/dlclose. Constructors of static objects are called from inside dlopen and destructors of static objects are called from dlclose.

What is about the threading environment in these cases, are multiple threads still running, is there a danger of constructors/destructors collisions on data with the other active threads?

Update:

In this case, I am a library developer, my question is what can I expect from applications using the library? I would not expect direct calls to the library in question while dopen/dlclose are in progress but constructors/destructors may have data collisions.

Also, my question is not about calling dlopen/dlclose multiple times.

Say I have a static instance of a class that takes a mutex to access some shared data, should I take this mutex in the destructor called from dlclose as a part of a cleanup?


Solution

  • is there a danger of constructors/destructors collisions on data with the other active threads?

    Yes: if the application is actively using your dlopened library in thread T1 and calls dlclose in another thread T2, that dlclose may yank the carpet from under T1's feet and cause it crash.

    You should tell your clients to not do that.

    should I take this mutex in the destructor called from dlclose as a part of a cleanup?

    No, doing so is pointless.

    Suppose T1 is currently in your library, but not accessing shared data. T2 performs dlclose (with or without acquiring the mutex), and unloads the library. The next instruction T1 executes (still in your library) will access code which has been unloaded, and will crash. You taking the mutex in the destructor will not prevent that crash.