C語言:哲學家吃飯問題

來源:互聯網
上載者:User

標籤:mem   thread   err   math.h   amp   main   意大利   cas   clu   

//五個哲學家圍坐在一起,兩人之間都放有一個叉子,意大利麵需要2個叉子吃,哲學家吃飯時候叉子只能拿左右手,哲學家除了吃飯時間其他時間都在思考
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <pthread.h>
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
//叉子作為mutex
pthread_mutex_t forkp[5] ;
void *eat_think(void *arg)
{
    //定義叉子編號
    char phi = *(char *)arg;
    int left,right;
    switch (phi){
        case ‘A‘:
            left = 5;
            right = 1;
            break;
        case ‘B‘:
            left = 1;
            right = 2;
            break;
        case ‘C‘:
            left = 2;
            right = 3;
            break;
        case ‘D‘:
            left = 3;
            right = 4;
            break;
        case ‘E‘:
            left = 4;
            right = 5;
            break;
    }

    int i;
    for(;;){
        sleep(rand()%4);//思考0~3秒
        pthread_mutex_lock(&forkp[left]);//拿起左手的叉子
        printf("哲學家 %c 拿起左手的叉子 %d\n", phi, left);
        if (pthread_mutex_trylock(&forkp[right]) == EBUSY){//拿起右手的叉子
            pthread_mutex_unlock(&forkp[left]);//如果右邊叉子被拿走放下左手的叉子
printf("哲學家 %c 放下左手的叉子 %d\n", phi, left); 
            continue;
        }
        printf("哲學家 %c 拿起右手的叉子 %d\n", phi, right);
        printf("哲學家 %c 在吃飯\n",phi);
        printf("--------------------------------\n");
                sleep(rand()%4);//吃0~3秒
        pthread_mutex_unlock(&forkp[left]);
        pthread_mutex_unlock(&forkp[right]);
    }
}
int main(){
    pthread_t A,B,C,D,E;

    int i;
    for (i = 0; i < 5; i++)
        pthread_mutex_init(&forkp[i],NULL);
    pthread_create(&A,NULL, eat_think, "A");
    pthread_create(&B,NULL, eat_think, "B");
    pthread_create(&C,NULL, eat_think, "C");
    pthread_create(&D,NULL, eat_think, "D");
    pthread_create(&E,NULL, eat_think, "E");

    pthread_join(A,NULL);
    pthread_join(B,NULL);
    pthread_join(C,NULL);
    pthread_join(D,NULL);
    pthread_join(E,NULL);
    return 0;
}

C語言:哲學家吃飯問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.