philosopher.c
来自「哲学家进餐经典算法的pthread多线程实现代码」· C语言 代码 · 共 77 行
C
77 行
#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 + =
减小字号Ctrl + -
显示快捷键?