zoukankan      html  css  js  c++  java
  • 哲学家问题

    每次获得一个筷子,会引起死锁的。

    解决的办法是,每次尝试去获取所需的两个筷子。第一次获取左边的,第二次获取右边的。

    只有当两个都获取到了,才吃东西。否则就要释放所有获得的筷子。

    这样就能避免死锁了。

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <pthread.h>
    
    pthread_mutex_t chopsticks[5];
    
    void fun(int i){
    
        
        int k = 0;    
        
        while(k<50){
    
    
            if(pthread_mutex_trylock(&chopsticks[i])==0){
    
                if(pthread_mutex_trylock(&chopsticks[(i+1)%5])==0){
                    
                printf("zhexuejia %d is eatinging
    ",i);k++;
                usleep(10);
                pthread_mutex_unlock(&chopsticks[i]);
                pthread_mutex_unlock(&chopsticks[(i+1)%5]);    
                
    
                }else{
    
                    
                    printf("zhexuejia %d is thinking
    ",i);k++;
                    pthread_mutex_unlock(&chopsticks[i]);
                    usleep(10);
    
                }
    
    
    
    
            }else{
    
                printf("zhexuejia %d is thinking
    ",i);k++;
                usleep(10);
    
            }
    
    
            
    
    
    
    
        }
    
    
    }
    
    int main(){
    
        int t = 0;
        while(t<5){
    
        pthread_mutex_init(&chopsticks[t],NULL);
        t++;
    
        }
    
        pthread_t tid1,tid2,tid3,tid4,tid5;
        pthread_create(&tid1,NULL,(void*)fun,0);
        pthread_create(&tid2,NULL,(void*)fun,1);
        pthread_create(&tid3,NULL,(void*)fun,2);
        pthread_create(&tid4,NULL,(void*)fun,3);
        pthread_create(&tid5,NULL,(void*)fun,4);
    
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
        pthread_join(tid3,NULL);
        pthread_join(tid4,NULL);
        pthread_join(tid5,NULL);
    
    
    
    
    
    }

  • 相关阅读:
    集合模拟斗地主
    泛型
    Iterator迭代器
    嵌入式应用开发过程中用到的函数
    Keil ,source insight使用技巧等
    Socket应用demo 获取IP
    tftp安装、配置,ubuntu联网设置
    C++基础三——类、结构体、联合体
    C++基础二——清华
    STM32笔记
  • 原文地址:https://www.cnblogs.com/wzben/p/5410742.html
Copyright © 2011-2022 走看看