![b7309e488753daddc774e527a6c80bec.png](https://img-blog.csdnimg.cn/img_convert/b7309e488753daddc774e527a6c80bec.png)
问题描述:在linux中使用pthread线程,并使用mutex互斥锁进行线程间的互斥时,当一个线程获取锁之后发生异常操作而退出使得没有正常释放这个锁,这个时候,其他的线程在访问获取这个锁时就会产生死锁等待的现象,影响了程序正常运行。
解决方法:gcc提供了一种机制,利用设置线程的属性PTHREAD_MUTEX_ROBUST和调用pthread_mutex_consistent函数进行更换锁的属主,让死锁等待的线程能正常运行下去。
以下通过实际代码测试:
#include #include #include #include #include #define handle_error_en(en, msg) do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)static pthread_mutex_t mtx;static void *original_owner_thread(void *ptr){ printf("[original owner] Setting lock..."); pthread_mutex_lock(&mtx); printf("[original owner] Locked. Now exiting without unlocking."); pthread_exit(NULL);//加锁后退出不释放锁}int main(int argc, char *argv[]){ pthread_t thr; pthread_mutexattr_t attr; int s; pthread_mutexattr_init(&attr); /* initialize the attributes object */ pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);//设置robust属性 pthread_mutex_init(&mtx, &attr); /* initialize the mutex */ pthread_create(&thr, NULL, original_owner_thread, NULL); sleep(2); /* "original_owner_thread" should have exited by now */ printf("[main thread] Attempting to lock the robust mutex."); s = pthread_mutex_lock(&mtx); if (s == EOWNERDEAD) {//lock失败后的返回值 printf("[main thread] pthread_mutex_lock() returned EOWNERDEAD"); printf("[main thread] Now make the mutex consistent"); s = pthread_mutex_consistent(&mtx);//调用函数进行更换锁的属主,也就是锁从以前拥有者更换为当起线程 if (s != 0) handle_error_en(s, "pthread_mutex_consistent"); printf("[main thread] Mutex is now consistent; unlocking"); s = pthread_mutex_unlock(&mtx); if (s != 0) handle_error_en(s, "pthread_mutex_unlock"); exit(EXIT_SUCCESS); } else if (s == 0) { printf("[main thread] pthread_mutex_lock() unexpectedly succeeded"); exit(EXIT_FAILURE); } else { printf("[main thread] pthread_mutex_lock() unexpectedly failed"); handle_error_en(s, "pthread_mutex_lock"); }}
编译时记得带上链接库-lpthread,运行结果:
![a7b2b0d475d0d8a01aac0e545fae0024.png](https://img-blog.csdnimg.cn/img_convert/a7b2b0d475d0d8a01aac0e545fae0024.png)
另外,这是线程间的互斥解锁情况,gcc 版本 4.4.7就能支持此种特性,如果mutex用在多个进程之间的情况,需要gcc的一定版本之后才能支持,经过笔者测试发现,在gcc 版本 4.8.5 20150623 (Red Hat 4.8.5-11) 能支持进程间的死锁自动释放。