4

I am doing C++ multithread programming. I use mutex to read and write a queue in order to avoid deadlock. Currently, I only launch 1 thread for

    pthread_mutex_lock(&the_mutex);

But, in GDB, my code is frozen here, it is pending.

Why ? there is only one thread !!!

thanks

user1002288
  • 4,860
  • 10
  • 50
  • 78
  • 1
    How do you initialize the mutex? – thkala Nov 06 '11 at 01:14
  • I use pthread_mutex_init(&mutex, NULL) inside a class contr. – user1002288 Nov 06 '11 at 01:40
  • Since you seem to assume that "the thread that locked it already can lock it again" you may be looking for _recursive mutexes_ (`PTHREAD_MUTEX_RECURSIVE`). Regarding that, see: http://stackoverflow.com/questions/187761/recursive-lock-mutex-vs-non-recursive-lock-mutex/1244997#1244997 - generally, it's possible to achieve this behaviour. But recursive locking also tends to allow for subtle bugs. – FrankH. Nov 07 '11 at 09:07

1 Answers1

6

From the pthread_mutex_lock() manual page:

If the mutex type is PTHREAD_MUTEX_NORMAL, deadlock detection shall not be provided. Attempting to relock the mutex causes deadlock. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results.

If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to recursively lock the mutex results in undefined behavior. Attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior. Attempting to unlock the mutex if it is not locked results in undefined behavior.

Bottom line: it's perfectly possible to cause a deadlock with only one thread if you try to lock a mutex that is already locked.

In case you are wondering, on Linux PTHREAD_MUTEX_DEFAULT is usually a synonym of PTHREAD_MUTEX_NORMAL, which in turn is what is used in the default mutex initializer.

thkala
  • 84,049
  • 23
  • 157
  • 201