死锁实例



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
#include
#include
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/

          





你可能感兴趣的:(进程间通信)