Search code examples
linuxmultithreadingmutexdeadlock

thread exit but still hold mutex


A thread which hold mutex died. Another thread will deadlock when it calls "pthread_mutex_lock", although I use "PTHREAD_MUTEX_ERRORCHECK" attribute.

#include <pthread.h>
#include <iostream>
#include <unistd.h>

using namespace std;

pthread_mutex_t mutex;

void *handler(void *)
{
    cout << "child thread" << endl;
    int ret = pthread_mutex_lock(&mutex);
    cout << "child ret: " << ret << endl;
    pthread_exit(NULL);
}

int main()
{
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);

    pthread_mutex_init(&mutex, &attr);
    pthread_mutexattr_destroy(&attr);

    pthread_t tid;
    pthread_create(&tid, NULL, handler, NULL);

    sleep(2);
    cout << "father awake" << endl;

    int ret = pthread_mutex_lock(&mutex);
    cout << "father ret: " << ret << endl;
    return 0;
}

Output:

enter image description here

[LINUX ENVIRONMENT]: Linux ubuntu 3.19.0-25-generic #26~14.04.1-Ubuntu SMP


Solution

  • You are perhaps thinking of the robust attribute of mutexes (pthread_mutexattr_setrobust()), rather than of the errorcheck type of mutex. A robust mutex would have notified your main thread that the holder of the mutex's lock had terminated with EOWNERDEAD.

    The PTHREAD_MUTEX_ERRORCHECK type, on the other hand, simply guards against three kinds of errors:

    1. attempting to recursively lock one's own locked mutex (not applicable here)
    2. attempting to unlock a mutex locked by another thread (not applicable here)
    3. attempting to unlock an unlocked mutex (not applicable here)