哲学家就餐 c语言代码
时间: 2024-12-24 22:05:44 浏览: 10
以下是一个用C语言实现的哲学家就餐问题的代码示例:
```c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_PHILOSOPHERS 5
#define THINKING 0
#define HUNGRY 1
#define EATING 2
int state[NUM_PHILOSOPHERS];
pthread_mutex_t mutex;
pthread_mutex_t s[NUM_PHILOSOPHERS];
void* philosopher(void* num);
void take_forks(int);
void put_forks(int);
void test(int);
void think();
void eat();
int main() {
int i;
pthread_t thread_id[NUM_PHILOSOPHERS];
pthread_mutex_init(&mutex, NULL);
for (i = 0; i < NUM_PHILOSOPHERS; i++)
pthread_mutex_init(&s[i], NULL);
for (i = 0; i < NUM_PHILOSOPHERS; i++)
pthread_create(&thread_id[i], NULL, philosopher, (void*)i);
for (i = 0; i < NUM_PHILOSOPHERS; i++)
pthread_join(thread_id[i], NULL);
for (i = 0; i < NUM_PHILOSOPHERS; i++)
pthread_mutex_destroy(&s[i]);
pthread_mutex_destroy(&mutex);
return 0;
}
void* philosopher(void* num) {
int id = (int)num;
while (1) {
think(id);
take_forks(id);
eat(id);
put_forks(id);
}
}
void take_forks(int id) {
pthread_mutex_lock(&mutex);
state[id] = HUNGRY;
printf("Philosopher %d is hungry.\n", id);
test(id);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&s[id]);
}
void put_forks(int id) {
pthread_mutex_lock(&mutex);
state[id] = THINKING;
printf("Philosopher %d is thinking.\n", id);
test((id + 4) % NUM_PHILOSOPHERS);
test((id + 1) % NUM_PHILOSOPHERS);
pthread_mutex_unlock(&mutex);
}
void test(int id) {
if (state[id] == HUNGRY && state[(id + 4) % NUM_PHILOSOPHERS] != EATING && state[(id + 1) % NUM_PHILOSOPHERS] != EATING) {
state[id] = EATING;
printf("Philosopher %d is eating.\n", id);
pthread_mutex_unlock(&s[id]);
}
}
void think(int id) {
printf("Philosopher %d is thinking.\n", id);
sleep(rand() % 3 + 1);
}
void eat(int id) {
printf("Philosopher %d is eating.\n", id);
sleep(rand() % 3 + 1);
}
```
这个代码实现了经典的哲学家就餐问题。每个哲学家都被模拟为一个线程,共享的筷子用互斥锁表示。代码使用了以下关键函数:
1. `philosopher`:每个哲学家的主循环,包含思考、取筷子、吃饭和放筷子。
2. `take_forks`:哲学家尝试拿起两边的筷子。
3. `put_forks`:哲学家放下筷子,并尝试唤醒左右两边的哲学家。
4. `test`:检查哲学家是否可以开始吃饭。
5. `think`和`eat`:模拟哲学家思考和吃饭的时间。
阅读全文