问题描述:在linux中使用pthread线程,并使用mutex互斥锁进行线程间的互斥时,当一个线程获取锁以后发生异常操作而退出促使没有正常释放这个锁,这个时侯linux软件下载,其他的线程在访问获取这个锁时才会形成死锁等待的现象linux死锁的解决方法,影响了程序正常运行。
解决方式: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...n"); pthread_mutex_lock(&mtx); printf("[original owner] Locked. Now exiting without unlocking.n"); 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.n"); s = pthread_mutex_lock(&mtx); if (s == EOWNERDEAD) {//lock失败后的返回值 printf("[main thread] pthread_mutex_lock() returned EOWNERDEADn"); printf("[main thread] Now make the mutex consistentn"); s = pthread_mutex_consistent(&mtx);//调用函数进行更换锁的属主,也就是锁从以前拥有者更换为当起线程 if (s != 0) handle_error_en(s, "pthread_mutex_consistent"); printf("[main thread] Mutex is now consistent; unlockingn"); 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 succeededn"); exit(EXIT_FAILURE); } else { printf("[main thread] pthread_mutex_lock() unexpectedly failedn"); handle_error_en(s, "pthread_mutex_lock"); } }
编译时记得带上链接库-lpthreadlinux 安装,运行结果:
另外,这是线程间的互斥解锁情况,gcc版本4.4.7才能支持此种特点,假如mutex用在多个进程之间的情况,须要gcc的一定版本以后才会支持,经过笔者测试发觉linux死锁的解决方法,在gcc版本4.8.520150623(RedHat4.8.5-11)能支持进程间的死锁手动释放。