diff --git a/Operating Systems.md b/Operating Systems.md index b70e635..06f3c9c 100644 --- a/Operating Systems.md +++ b/Operating Systems.md @@ -100,47 +100,91 @@ wait操作:执行wait操作的进程进入条件变量链末尾,唤醒紧急 生产者-消费者问题 > 问题描述:使用一个缓冲区来存放数据,只有缓冲区没有满,生产者才可以写入数据;只有缓冲区不为空,消费者才可以读出数据 -> -> ```c -> // 伪代码描述 -> // 定义信号量 full记录缓冲区物品数量 empty代表缓冲区空位数量 mutex为互斥量 -> semaphore full = 0, empty = n, mutex = 1; -> -> // 生产者进程 -> void producer(){ -> do{ -> P(empty); -> P(mutex); -> -> // 生产者进行生产 -> -> V(mutex); -> V(full); -> } while(1); -> } -> -> void consumer(){ -> do{ -> P(full); -> P(mutex); -> -> // 消费者进行消费 -> -> V(mutex); -> V(empty); -> } while(1); -> } -> -> ``` -> -> -> -> + +代码实现: +```c +// 伪代码描述 +// 定义信号量 full记录缓冲区物品数量 empty代表缓冲区空位数量 mutex为互斥量 +semaphore full = 0, empty = n, mutex = 1; + +// 生产者进程 +void producer(){ + do{ + P(empty); + P(mutex); + + // 生产者进行生产 + + V(mutex); + V(full); + } while(1); +} + +void consumer(){ + do{ + P(full); + P(mutex); + + // 消费者进行消费 + + V(mutex); + V(empty); + } while(1); +} + +``` +
哲学家就餐问题 - +> 问题描述:有五位哲学家围绕着餐桌坐,每一位哲学家要么思考,要么吃饭。为了吃饭,哲学家必须拿起两双筷子(分别放于左右两端)不幸的是,筷子的数量和哲学家相等,所以每只筷子必须由两位哲学家共享。 + +代码实现: +```c +#define N 5 // number of philosopher +#define LEFT (i + N - 1)%N // number of i's left neighbors +#define RIGHT (i + 1)%N // number of i's right neighbors +#define THINKING 0 +#define HUNGRY 1 +#define EATING 2 +typedef int semaphore; +int state[N]; // array to keep track of everyone's state +semaphore mutex = 1; // mutual exclusion of critical region +semaphore s[N]; + +void philosopher(int i) { + while (TRUE) { + think(); + take_forks(i); + eat(); + put_forks(i); + } +} + +void take_forks(int i) { + down(&mutex); // enter critical region + state[i] = HUNGRY; // record that i is hungry + test_forks(i); // try to acquire two forks + up(&mutex); // exit critical region + down(&s[i]); // block if forks are not acquired +} + +void put_forks(int i) { + down(&mutex); // enter critical region + state[i] = THINKING; // record that has finished eating + test_forks(LEFT); // see if left neighbor can now eat + test_forks(RIGHT); // see if right neighbor can now eat + up(&mutex); // exit critical region +} + +void test_forks(int i) { + if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) { + state[i] = EATING; + up(&s[i]); + } +} +```