38
votes

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;
1
If you use a static mutex, you will serialize the use of all the instances of your class, completely negating any benefit you may gain through multithreading. Are you sure you want this? - John Dibling
@John Dibling Yes, only creating and destroying the objects will be protected - it will not happen too often. The rest of the time the instances will be used without locking the mutex and it should be quite efficient. - Dmitry Yudakov
@Dmity: Which leads me to my next question: are you sure it will be safe to use the instances without locking? - John Dibling
@John Dibling The 3rd party library provide some locking mechanism that's supposed to guaranty thread-safe work, but they need existing objects - my tests showed that it's working. It seems though that concurrent creating of these objects in not very safe. - Dmitry Yudakov
Remember that a static data member of a class will be shared among all instances of the class AND instances of derived classes. You may want to reconsider the static qualifier. - Thomas Matthews

1 Answers

58
votes

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.