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

仅仅允许4个人同时就餐

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

using namespace std;

#define THINK(i) printf("ph[%d] is thinking...
", i)
#define EAT(i) printf("ph[%d] eats.
", 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;
}

原文地址:https://www.cnblogs.com/svitter/p/4006126.html