操作系统经典同步互斥问题——哲学家就餐

仅仅允许4个人同时就餐

#include <iostream>
#include <mutex>
#include <cstdio>
#include <thread>
#include <semaphore.h>

using namespace std;

#define THINK(i) printf("ph[%d] is thinking...\n", i)
#define EAT(i) printf("ph[%d] eats.\n", i)

void P(mutex &mt)
{
    mt.lock();
}

void V(mutex &mt)
{
    mt.unlock();
}

void P(sem_t* sem)
{
    if(sem_wait(sem))
        perror("P error!");
}
void V(sem_t* sem)
{
    if(sem_post(sem))
        perror("V error!");
}

// 加入unistd.h出现问题,似乎与thread的兼容性比较差,于是重写
void delay()
{
    int sum=0;
    for(int i = 0; i < 10000000; i++)
        sum += i;
}

mutex fork[5];
sem_t room;

void init()
{
    sem_init(&room, 0, 4);
}

void philosopher (int i)
{
    for(int j = 0; j < 5; j++)
    {
        THINK(i);
        P(&room);
        P(fork[i]);
        P(fork[(i+1)%5]);
        EAT(i);
        V(&room);
        V(fork[i]);
        V(fork[(i+1)%5]);
    }
}


int main()
{
    init();
    thread t[] = {
        thread(philosopher, 0),
        thread(philosopher, 1),
        thread(philosopher, 2),
        thread(philosopher, 3),
        thread(philosopher, 4),
    };
        
    
    for(int k = 0; k < 5; k++)
        t[k].join();
    
    return 0;
}

posted @ 2014-10-04 16:46  svtter  阅读(409)  评论(0编辑  收藏  举报