What happens when I do a pthread_mutex_init on an already locked pthread_mutex_t?

时间:2016-04-25 09:10:20

标签: c++ multithreading pthreads mutex

My mutex class is defined:-

class Mutex{
    static pthread_mutex_t mutex;
public:
    Mutex(){
        pthread_mutex_init(&mutex, NULL);
        while(pthread_mutex_trylock(&mutex)){
            sleep(2000);
        }
    }
    virtual ~Mutex(){
        pthread_mutex_unlock(&mutex);
        pthread_mutex_destroy(&mutex);
    }
};

The functions I am trying to apply the mutual exclusion to use this class like this:-

void doSomething(){
    Mutex mutex;
    // do something
}

This way when the constructor is called, the mutex is initialized and it tries to obtain the lock on that mutex. And when it goes out of scope from that function, it automatically gets destroyed.

But if one thread has a lock on the mutex, another thread tries to run pthread_mutex_init on it, what exactly happens? Will the thread that has the lock be overridden?

1 个答案:

答案 0 :(得分:5)

Pretty easy, from POSIX.1-2013:

Attempting to initialize an already initialized mutex results in undefined behavior.

That's why you have an alternative way of initializing mutexes:

// in your .cpp somewhere
pthread_mutex_t Mutex::mutex = PTHREAD_MUTEX_INITIALIZER;

Apart from this, logically speaking, your class seems very questionable. Do you really want to have one global lock for all users of Mutex, no matter what they're doing? You should employ fine grained locks, or you'll artificially limit your own scalability via software lockout.