用C语言代码写出哲学家进餐经典同步问题
时间: 2024-05-05 08:22:47 浏览: 20
哲学家进餐问题是经典的同步问题,用C语言代码实现如下:
```c
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define N 5 // 哲学家数量
pthread_t philosophers[N];
sem_t forks[N];
void *philosopher(void *arg) {
int id = *(int *)arg;
int left = id;
int right = (id + 1) % N;
while (1) {
printf("Philosopher %d is thinking\n", id);
sleep(1);
printf("Philosopher %d is hungry\n", id);
sem_wait(&forks[left]); // 拿起左边的叉子
printf("Philosopher %d picks up left fork\n", id);
sem_wait(&forks[right]); // 拿起右边的叉子
printf("Philosopher %d picks up right fork\n", id);
printf("Philosopher %d is eating\n", id);
sleep(1);
sem_post(&forks[right]); // 放下右边的叉子
printf("Philosopher %d puts down right fork\n", id);
sem_post(&forks[left]); // 放下左边的叉子
printf("Philosopher %d puts down left fork\n", id);
}
return NULL;
}
int main() {
int i;
for (i = 0; i < N; i++) {
pthread_create(&philosophers[i], NULL, philosopher, &i);
sem_init(&forks[i], 0, 1);
}
for (i = 0; i < N; i++) {
pthread_join(philosophers[i], NULL);
sem_destroy(&forks[i]);
}
return 0;
}
```
在这个程序中,`N` 表示哲学家的数量,`pthread_t philosophers[N]` 定义了 `N` 个哲学家的线程,`sem_t forks[N]` 定义了 `N` 把叉子的信号量。
每个哲学家的线程通过 `philosopher()` 函数实现,其中 `id` 表示哲学家的编号,`left` 和 `right` 分别表示左边和右边的叉子的编号。
在 `philosopher()` 函数中,每个哲学家会不断地思考、感到饥饿、拿起叉子、进餐、放下叉子。其中,`sem_wait()` 表示等待信号量,`sem_post()` 表示释放信号量。
在 `main()` 函数中,先创建 `N` 个哲学家的线程,并初始化 `N` 把叉子的信号量。然后等待所有哲学家的线程执行完毕,最后销毁 `N` 把叉子的信号量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)