Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static mutex in a class

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` 
  1. Do I need some special initialization of such static member?

  2. Is there anything wrong about using static mutex?


Edit: Linking problem is fixed with correct definition in cpp

boost::mutex MyClass::mx; 
like image 517
Dmitry Yudakov Avatar asked Mar 17 '10 14:03

Dmitry Yudakov


People also ask

Can a mutex be static?

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.

How do you initialize static mutex?

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.

Are mutexes fair?

Mutexes can be fair or unfair. A fair mutex lets threads through in the order they arrived. Fair mutexes avoid starving threads.

What is a global mutex?

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.


1 Answers

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.

like image 59
Stephen C. Steel Avatar answered Sep 24 '22 10:09

Stephen C. Steel