I have a class that I can have many instances of. Inside it creates and initializes some members from a 3rd party library (that use some global variables) and is not thread-safe.
I thought about using static boost::mutex, that would be locked in my class constructor and destructor. Thus creating and destroying instances among my threads would be safe for the 3rd party members.
class MyClass { static boost::mutex mx; // 3rd party library members public: MyClass(); ~MyClass(); }; MyClass::MyClass() { boost::mutex::scoped_lock scoped_lock(mx); // create and init 3rd party library stuff } MyClass::~MyClass() { boost::mutex::scoped_lock scoped_lock(mx); // destroy 3rd party library stuff }
I cannot link because I receive error:
undefined reference to `MyClass::mx`
Do I need some special initialization of such static member?
Is there anything wrong about using static mutex?
Edit: Linking problem is fixed with correct definition in cpp
boost::mutex MyClass::mx;
Because the default constructor is constexpr , static mutexes are initialized as part of static non-local initialization, before any dynamic non-local initialization begins. This makes it safe to lock a mutex in a constructor of any static object.
If you have a C99 conforming compiler you can use P99 to do your initialization: static pthread_mutex_t mutexes[NUM_THREADS] = { P99_DUPL(NUM_THREADS, PTHREAD_MUTEX_INITIALIZER) }; This just repeats the token sequence PTHREAD_MUTEX_INITIALIZER, the requested number of times.
Mutexes can be fair or unfair. A fair mutex lets threads through in the order they arrived. Fair mutexes avoid starving threads.
The global mutex is a recursive mutex with a name of "QP0W_GLOBAL_MTX". The global mutex is not currently used by the pthreads run-time to serialize access to any system resources, and is provided for application use only. The maximum number of recursive locks by the owning thread is 32,767.
You have declared, but not defined your class static mutex. Just add the line
boost::mutex MyClass::mx;
to the cpp file with the implementation of MyClass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With