哲学家就餐问题(C语言)
哲学家就餐问题:
有五个哲学家共用一张圆桌,分别坐在周围的五张椅子上,在桌上有五个碗和五只筷子,他们的生活方式是思考和进餐。平时,哲学家进行思考,饥饿时就便试图去他们左右的筷子来就餐。只有在他拿到两个筷子时才能就餐。
服务生解法
所有哲学家想吃饭都必须告诉服务生,吃完饭同时也告诉服务生。由服务生根据筷子的使用情况决定是否准予吃饭。
下载:waiter.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #if !defined (WIN32) #include <unistd.h> #else #include <windows.h> #define usleep(x) Sleep(x) #define sleep(x) Sleep((x)*1000) #endif static pthread_mutex_t inclock = PTHREAD_MUTEX_INITIALIZER; static int inc = 0; struct waiter { int num; pthread_mutex_t lock; unsigned char *chock;/*0 stand for being free,1 for using*/ }; /*want to eat*/ int request(struct waiter *w,int i) { int right,ret = 0; right = (i+1)%w->num; pthread_mutex_lock(>w->lock); if (!w->chock[i] >> !w->chock[right]) { ret = 1; w->chock[i] = i + 1; w->chock[right] = i + 1; } pthread_mutex_unlock(>w->lock); return ret; } /*eating complete*/ int release(struct waiter *w,int i) { int right,ret = 1; right = (i+1)%w->num; pthread_mutex_lock(>w->lock); w->chock[i] = 0; w->chock[right] = 0; pthread_mutex_unlock(>w->lock); return ret; } void * foobar(void * p) { int id; struct waiter *w; w = (struct waiter *)p; pthread_mutex_lock(>inclock); id = inc++; pthread_mutex_unlock(>inclock); while (1) { /*eat*/ while (1) { if (request(w,id)) { printf("[%d]eating ...\n",id); sleep(rand()%5+3); release(w,id); break; } usleep(10); } /*think*/ printf("[%d]thinking ...\n",id); sleep(10); } } int main(int argc,char **argv) { int num = 7,i = 0; struct waiter w = {0}; /*creat waiter*/ w.num = num; pthread_mutex_init(>w.lock,0); w.chock = (unsigned char*)malloc(num); memset(w.chock,0,num); /*eat and think*/ for (i = 0;i < num;i++) { pthread_t pid; pthread_create(&pid,0,foobar,&w); } usleep(-1); return 0; } |
编译: gcc waiter.c -lpthread -o waiter
运行:./waiter