PTHREAD_MUTEX_INITIALIZER inside C++ member function cannot compile?

前端 未结 4 1847
遇见更好的自我
遇见更好的自我 2020-12-17 02:00
class A {
    public:
        A();
    private:
        pthread_mutex_t mu;
};

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

Ca

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 02:10

    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.

提交回复
热议问题