Using static mutex in a class

47,998

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.

Share:
47,998
Dmitry Yudakov
Author by

Dmitry Yudakov

Updated on March 18, 2020

Comments

  • Dmitry Yudakov
    Dmitry Yudakov about 4 years

    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;
    
  • Dmitry Yudakov
    Dmitry Yudakov about 14 years
    10x, it did fix the linking problem. I tried defining it before but missed the type before MyClass::mx
  • Gr-Disarray
    Gr-Disarray over 2 years
    Why is this required? and what is the difference between declaration and definition?