持有互斥锁的线程死了。另一个线程在调用“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;
}
输出:
[LINUX ENVIRONMENT]: Linux ubuntu 3.19.0-25-generic#26~14.04.1-Ubuntu SMP
答案 0 :(得分:1)
您可能正在考虑互斥锁(pthread_mutexattr_setrobust()
)的健壮属性,而不是互斥锁的错误检查类型。一个强大的互斥锁会通知你的主线程,互斥锁的持有者已经终止了EOWNERDEAD。
另一方面,PTHREAD_MUTEX_ERRORCHECK类型只是guards against three kinds of errors:
答案 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
所看到的那样,其状态再次标记为一致。