#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <pthread.h>
#define MAX_BUFFER_SIZE 5
#define SHM_MODE 0600
#define SEM_MODE 0600
#define N 5
// Define your variables here
pthread_t philosophers[N]; // 哲学家线程
int forks[N]; // 哲学家叉子状态:1表示已被占用,0表示可用
pthread_mutex_t mutex; // 互斥锁,用于保护临界区
// P Operation
void Wait(int sem_id, int sem_num)
{
struct sembuf sb;
sb.sem_num = sem_num;
sb.sem_op = -1;
sb.sem_flg = 0;
semop(sem_id, &sb, 1);
}
// V Operation
void Signal(int sem_id, int sem_num)
{
struct sembuf sb;
sb.sem_num = sem_num;
sb.sem_op = 1;
sb.sem_flg = 0;
semop(sem_id, &sb, 1);
}
void think(int i)
{
printf("The philosopher of %d is thinking.\n", i);
sleep(1);
}
void eat(int i)
{
printf("The philosopher of %d is eating.\n", i);
sleep(1);
}
void *philosopher(void *param)
{
int i = *(int *)param;
while (1)
{
think(i);
// Take forks
Wait(mutex, i);
forks[i] = 1;
forks[(i + 1) % N] = 1;
Signal(mutex, i);
// Eat
eat(i);
// Put forks
Wait(mutex, i);
forks[i] = 0;
forks[(i + 1) % N] = 0;
Signal(mutex, i);
printf("The philosopher of %d has finished eating.\n", i);
}
}
int main()
{
// Initialize semaphores and shared memory
int i;
// 初始化叉子状态和互斥锁
for (i = 0; i < N; i++)
{
forks[i] = 0;
}
pthread_mutex_init(&mutex, NULL);
// 创建哲学家线程
int philosopher_ids[N];
for (i = 0; i < N; i++)
{
philosopher_ids[i] = i;
pthread_create(&philosophers[i], NULL, philosopher, &philosopher_ids[i]);
}
// 等待哲学家线程结束
for (i = 0; i < N; i++)
{
pthread_join(philosophers[i], NULL);
}
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
printf("Parent Process is over!\n");
fflush(stdout);
return 0;
}