线程退出但仍保持互斥锁

时间:2015-12-03 01:53:24

标签: linux multithreading mutex deadlock

持有互斥锁的线程死了。另一个线程在调用“pthread_mutex_lock”时会死锁,尽管我使用“PTHREAD_MUTEX_ERRORCHECK”属性。

#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;
}

输出:

enter image description here

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

2 个答案:

答案 0 :(得分:1)

您可能正在考虑互斥锁(pthread_mutexattr_setrobust())的健壮属性,而不是互斥锁的错误检查类型。一个强大的互斥锁会通知你的主线程,互斥锁的持有者已经终止了EOWNERDEAD。

另一方面,PTHREAD_MUTEX_ERRORCHECK类型只是guards against three kinds of errors

  1. 尝试递归锁定自己锁定的互斥锁(此处不适用)
  2. 尝试解锁由另一个线程锁定的互斥锁(此处不适用)
  3. 尝试解锁未锁定的互斥锁(此处不适用)

答案 1 :(得分:0)

这是使用pthread_mutexattr_setrobust调用的一个小例子,允许将从未解锁的mutex设置回一致状态:

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

pthread_mutex_t lock;

void dropped_thread(void)
{
    printf("Setting lock...\n");
    pthread_mutex_lock(&lock);
    printf("Lock set, now exiting without unlocking...\n");
    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    pthread_t lock_getter;
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); 
    pthread_mutex_init(&lock, &attr);
    pthread_mutexattr_destroy(&attr);
    pthread_create(&lock_getter, NULL, (void *) dropped_thread, NULL);
    sleep(2);

    printf("Inside main\n");
    printf("Attempting to acquire unlocked mutex?\n");

    pthread_mutex_consistent(&lock);
    pthread_mutex_unlock(&lock);
    pthread_mutex_lock(&lock);

    printf("Successfully acquired lock!\n");
    pthread_mutex_destroy(&lock);
    return 0;
}

正如您在设置mutex健壮性后调用pthread_mutex_consistent所看到的那样,其状态再次标记为一致。