user1002288
user1002288

Reputation: 5040

only one thread may cause deadlock or freezing the program on Linux?

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

Upvotes: 4

Views: 1350

Answers (1)

thkala
thkala

Reputation: 86353

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.

Upvotes: 6

Related Questions