Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If you unlock an already unlocked mutex, is the behavior undefined?

If you unlock an already unlocked mutex, is the behavior unsafe, safe, or undefined?

The purpose of the question is related to the following code, where I don't know if it would be better to unlock the mutexes within the if block, or just outside the if block.

    // This chunk of code makes dual locking semi-autonomous.     int c_lckd = 0, q_lckd = 0;     if (pthread_mutex_trylock(&crunch_mutex) == 0) c_lckd = 1;     if (pthread_mutex_trylock(&queue_mutex) == 0) q_lckd = 1;     if (q_lckd && !c_lckd) { QUEUE_UNLOCK; q_lckd = 0; }     else if (c_lckd && !q_lckd) { CRUNCH_UNLOCK; c_lckd = 0; }      if (c_lckd && q_lckd) {       printf("cr = %d, max = %d, cnt = %d\n",         crunching, max_crunching, queue_count(conn_queue));       if (crunching < max_crunching && queue_count(conn_queue)) {         pthread_t tid =           pthread_create(             &tid,             NULL,             crunch_conn,             (void *)queue_dequeue(conn_queue)           );         crunching++;       }       CRUNCH_UNLOCK QUEUE_UNLOCK     } 

Thanks, Chenz

like image 1000
Crazy Chenz Avatar asked Nov 22 '09 13:11

Crazy Chenz


People also ask

What happens if you unlock a mutex that is already unlocked?

If a thread attempts to unlock a mutex that it has not locked or a mutex that is unlocked, an error is returned. If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior.

What happens if you dont unlock the mutex?

If you don't, then a typical mutex is held in process memory and will simply cease to exist along with anything that might have access to it when the process terminates.

Can a mutex be unlock by another thread?

A normal mutex cannot be locked repeatedly by the owner. Attempts by a thread to relock an already held mutex, or to lock a mutex that was held by another thread when that thread terminated, cause a deadlock condition. A recursive mutex can be locked repeatedly by the owner.

Does mutex unlock order matter?

No, only the order of acquisition is important. As long as you hold them, you can release Mutexes in any order. It may be more "efficient" if work can be done somewhere else with only one of the Mutexes to have a specific order of release, but it's still deadlock-free.


1 Answers

For pthreads it will result in undefined behaviour. From the man page for pthread_mutex_unlock:

Calling pthread_mutex_unlock() with a mutex that the calling thread does not hold will result in undefined behavior.

Other mutexes will have their own behviour. As others have stated, it's best to read the manual for whichever mutex you're using.

like image 79
Glen Avatar answered Sep 19 '22 13:09

Glen