PTHREAD_MUTEX_INITIALIZER inside C++ member function cannot compile?

Viewed 6635
class A {
    public:
        A();
    private:
        pthread_mutex_t mu;
};

A::A()
{
    mu = PTHREAD_MUTEX_INITIALIZER;  //cannot compile
}

Can't I initialize pthread_mutex_t inside a class member function?

4 Answers

I like the answers from @askmish & @Diego. I like also what @Flexo explained.

But just as an option, if you are intent on initializing with the PTHREAD_MUTEX_INITIALIZER macro, what you can do is, make the mutex declaration inside the class definition static like this:

class A {
    public:
        A();
    private:
        static pthread_mutex_t mu;
};

And then you can initialize this static mutex in your source file BUT outside any member function, like this:

class A {
    public:
        A();
    private:
        static pthread_mutex_t mu;
};

pthread_mutex_t A::mu = PTHREAD_MUTEX_INITIALIZER;

A::A()
{
}

Your options:

  • So either you keep the macro and go static (as shown here). OR,
  • you keep the declaration of the mutex the same (non-static) but use the pthread_mutex_init() function (as others have indicated) inside your member-function.
Related