Linux 多线程 线程中段退出 互斥量解锁问题

本文通过示例探讨了在Linux多线程编程中,由于线程突然退出(如pthread_exit或pthread_cancel)导致的互斥量未解锁问题,进而引起死锁的情况。解决方案包括在退出前解锁或使用pthread_cleanup_push和pthread_cleanup_pop确保在异常情况下正确解锁互斥量。
摘要由CSDN通过智能技术生成

1.      在lock与unlock之间,调用pthread_exit 或者在线程外部调用pthread_cancel

其他线程被永久死锁

例子:

#include<stdio.h>

#include<pthread.h>

#include<stdlib.h>

 

pthread_mutex_tm;

void * runodd(void* d)

{

int  i=0;

for(i=1;;i+=2)

{

      pthread_mutex_lock(&m);

      printf(“%d\n”,i);

      if(i>100000)

      {

              pthread_exit(0);

      }

      pthread_mutex_unlock(&m);

}

 

 

void * runeven(void*d)

{

int i=0;

for(i=0;;i+=2)

{

     pthread_mutex_lock(&m);

     printf(“%d\n”,i);

     pthread_mutex_unlock(&m);

}

}

 

 

void  main()

{

      pthread_t todd,tevent;

      pthread

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值