⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 philosopher.c

📁 哲学家进餐经典算法的pthread多线程实现代码
💻 C
字号:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#define N 5#define BusyEating 1#define BusyThinking 1#define Left(p) (p)#define Right(p) (((p)+1)%N)typedef int *semaphore;semaphore chopstick[N];semaphore init_semaphore(){     int *s = malloc(2*sizeof(int));     pipe(s);     return s;}void wait(semaphore s){     int junk;     read(s[0], &junk, 1);}void signal(semaphore s){     write(s[1], "x", 1);}void pick_up(int me){     if (me==0) {	  wait(chopstick[Right(me)]);	  printf("philosopher %d picks up right chopstick\n", me);	  sleep(1);	  wait(chopstick[Left(me)]);	  printf("philosopher %d picks up left chopstick\n", me);     } else {	  wait(chopstick[Left(me)]);	  printf("philosopher %d picks up left chopstick\n", me);	  sleep(1);	  wait(chopstick[Right(me)]);	  printf("philosopher %d picks up right chopstick\n", me);     }}void put_down(int me){     signal(chopstick[Left(me)]);     signal(chopstick[Right(me)]);}void philosopher(int me){     int i;     for (i=1; ; i++) {	  pick_up(me);	  printf("philosopher %d eating [%d]\n", me, i);	  sleep(BusyEating);	  put_down(me);	  printf("philosopher %d thinking\n", me);	  sleep(BusyThinking);     }}int main(){     int i;     for (i=0; i<N; i++) {	  chopstick[i] = init_semaphore();	  signal(chopstick[i]);     }     for (i=0; i<N-1; i++) if (fork()==0) break;     philosopher(i);	     return 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -