linux中original_解决linux下的mutex互斥锁死锁的一种方法

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

另外,这是线程间的互斥解锁情况,gcc 版本 4.4.7就能支持此种特性,如果mutex用在多个进程之间的情况,需要gcc的一定版本之后才能支持,经过笔者测试发现,在gcc 版本 4.8.5 20150623 (Red Hat 4.8.5-11) 能支持进程间的死锁自动释放。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值