//liux版本
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define N 8
#define LEFT (i+(N-1))%N
#define RIGHT (i+1)%N
#define THINKING 0 //不吃
#define HUNGRY 1//准备吃
#define EATING 2//在吃
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//哲学家状态转换锁
sem_t s[N];//哲学家信号量
int state[N];//哲学家状态
pthread_t thrd[N];//哲学家动作线程
int test(int i)
{
if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING){
//左右2个人都不在吃,则自己吃
state[i] = EATING;
printf("philosopher %d eating...\n",i);
sem_post(&s[i]);
return 1;
}
return 0;
}
void think(int i)
{
//printf("philosopher %d thinking...\n",i);
sleep(2);
//printf("philosopher %d thinking...over\n",i);
}
void take_forks(int i)
{
pthread_mutex_lock(&mutex);
state[i] = HUNGRY;
//看左右其他2个人是否在吃,都不在吃的时候,此人可吃,否则阻塞
int eating = test(i);
pthread_mutex_unlock(&mutex);
//test内如果在吃则up semaphore,下面down semaphore会立即返回,否则阻塞
sem_wait(&s[i]);
//只要sem_wait返回,则此人必定在吃,原因如下:
//1、在吃的话,sem_wait立即返回
//2、不在吃阻塞后,等他的左右2人吃完后驱动此人吃,也会导致up semaphore
if (i%2 == 0 && i >=4){
sleep(3);
printf("philosopher %d eating(3)...over\n",i);
}
else{
sleep(2);
printf("philosopher %d eating(2)...over\n",i);
}
}
void put_forks(int i)
{
//某人吃完,放叉子
pthread_mutex_lock(&mutex);
state[i] = THINKING;
//驱动左右2个人去吃
test(LEFT);
test(RIGHT);
pthread_mutex_unlock(&mutex);
}
void* philosopher(void* arg)
{
int i = *(int*)(arg);
printf("thread %d run...\n",i);
while(1){
think(i);
take_forks(i);
put_forks(i);
}
return NULL;
}
main()
{
int i = 0;
for (i = 0; i < N; i++){
sem_init(&s[i], 0, 0);
}
for (i = 0; i < N; i++){
pthread_create(&thrd[i],NULL,philosopher,&i);
}
for (i = 0; i < N; i++){
pthread_join(thrd[i], NULL);
}
for (i = 0; i < N; i++){
sem_destroy(&s[i]);
}
return 0;
}