信号量(semaphore),互斥锁(mutex)解决哲学家死锁问题

来源:互联网 发布:人工智能培训就业班 编辑:程序博客网 时间:2024/06/06 01:40

/*
author   : youfl
func     : 哲学家吃饭问题
descript :
    哲学家吃饭死锁问题,会产生死锁的主要原因是哲学家会同时拿起左边的筷子
    同时都在等右边的筷子释放,此处可以使用信号量,控制资源数量为总资源数
    量NUM - 1,在已经有NUM - 1 的筷子被使用的情况下,就不能有人再拿左边的
    筷子了进而保证哲学家不能同时获取到左边的筷子,从而解决死锁问题。  

contact:393639665@qq.com


*/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
//此处是自己用条件变量实现的信号量处理接口,用#include <semaphore.h>替
//代"semaphore_xx.h"即可
#include "semaphore_xx.h"

#define NUM 5
pthread_mutex_t chopsticks[NUM];

using namespace sem_xx;
sem_t semm;

const char * Philosophers[] = {"A","B","C","D","E"};

void * Philosopher(void * p){  
    int * user = new int;
    *user = *(int *)p;
    int left, right;
    left = ((*user) + 5 - 1) % NUM;
    right = ((*user) + 1) %NUM;
   
    while(1){       
        sleep(rand()%5);
        sem_wait(&semm);

        const char * name = Philosophers[(*user)];

        pthread_mutex_lock(chopsticks + left);
        printf("Philosopher %s fetches chopstick %d\n",name, left+1);
        sleep(rand()%2);
        pthread_mutex_lock(chopsticks + right);
        printf("Philosopher %s fetches chopstick %d\n",name, right+1);
        sleep(rand()%5);
        pthread_mutex_unlock(chopsticks + right);
        pthread_mutex_unlock(chopsticks + left);
        printf("Philosopher %s droped chopsticks %d %d\n",name, left+1, right+1);
        sem_post(&semm);
    }
}
int main(){
    int i = 0;
    pthread_t array[NUM];
   
    sem_init(&semm, NUM - 1);
    while(i<NUM)
        pthread_mutex_init(chopsticks + i++, NULL);
       
    for(int j = 0; j<NUM; j++){
        pthread_create(array + j, NULL, &Philosopher, &j);
        sleep(1);
    }
   
    for(int j = 0; j<NUM; j++)
        pthread_join(array[j], NULL);
    return 0;
}

 

ps: "semaphore_xx.h" 见下篇 条件变量实现的信号量处理接口