死锁实例



1、死锁实例1 ,哲学家饿死

pthread_mutex_t         dinner_lock = PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t         dinner_cond = PTHREAD_COND_INITIALIZER;

int                                 order = 0;

sem_t                         dinner_sem;

int sem_value  = 0;

void *dinner_proc(void *param)

{

      int                index = *(int *)param;

     printf("index  value is %d\n",index);
     pthread_mutex_lock(&dinner_lock); 
      sem_wait(&dinner_sem);              
      pthread_mutex_unlock(&dinner_lock);  
      sleep(1);        //这里很重要,去掉sleep的话部分线程会继续执行,不是所有的线程都死锁。
       printf("ready to get second chopstick.. sem_value is %d\n",sem_value);

        
      sem_wait(&dinner_sem);        /* dead lock */

      printf("%d got second chopstick..\n", index);

  
      sleep(3);

      printf("index %d eat dinner... \n",index);

     
      sem_post(&dinner_sem);

      pthread_exit(0);

}


2、死锁实例2(强制kill某一线程)

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t m;

void handle(void *d)
{
        printf("退出后的调用!\n");
        pthread_mutex_unlock(&m);
}
void *runodd(void *d)
{
    
       
        pthread_cleanup_push(handle,0);
        int i=0;

        for(i=1;;i+=2)
        {
            printf("jiangxin enter the runodd\n");
                pthread_mutex_lock(&m);
                printf("奇数:%d\n",i);
                usleep(100);
                pthread_mutex_unlock(&m);
                pthread_cleanup_pop(0);
        }
}
void *runeven(void *d)
{
        int i=0;
        for(i=0;;i+=2)
        {
                pthread_mutex_lock(&m);
                printf("偶数:%d\n",i);
                usleep(100);
                pthread_mutex_unlock(&m);
        }
}
void main()
{
        pthread_t todd,teven;
        pthread_mutex_init(&m,0);
        pthread_create(&todd,0,runodd,0);
        pthread_create(&teven,0,runeven,0);
        sleep(5);
        printf("外部强制停止todd线程\n");
        pthread_cancel(todd);
        pthread_join(todd,(void**)0);
        pthread_join(teven,(void**)0);
        pthread_mutex_destroy(&m);
}


使用 pstack 和 gdb 工具对死锁程序进行分析

3、  Linux 上分析死锁问题的简单方法 https://www.ibm.com/developerworks/cn/linux/l-cn-deadlock/

          




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值