信号量(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" 见下篇 条件变量实现的信号量处理接口
- 信号量(semaphore),互斥锁(mutex)解决哲学家死锁问题
- 互斥锁(mutex) VS 信号量(semaphore)
- java多线程 信号量(Semaphore),死锁
- 关于用信号量Semaphore实现互斥锁Mutex
- Semaphore And Mutex - 信号量与互斥锁
- 互斥锁Mutex与信号量Semaphore的区别
- 互斥锁Mutex与信号量Semaphore的区别
- 用信号量解决哲学家就餐问题
- c# Semaphore(信号量)
- 信号量(Semaphore)
- 信号量(semaphore)
- 信号量(Semaphore) 例子
- Semaphore(信号量)
- Semaphore(信号量)理解
- 信号量(Semaphore)
- 信号量(Semaphore)
- 三、信号量(semaphore)
- c# Semaphore(信号量)
- 第二篇 求两数正差值图片
- magento custom category api (1) --- collectiontree
- oracle简单学习总结(六)——数据库事务
- Flex Application 初始化事件的顺序
- C# DevExpress 的gridControl或gridView数据导出失败解决方法
- 信号量(semaphore),互斥锁(mutex)解决哲学家死锁问题
- C#多个项目如何共用文件
- hadoop 学习笔记
- 用条件变量(Condition Variable)实现信号量(Semaphore)
- 递归的好处,递归的运用例题
- HKLM\SYSTEM\CurrentControlSet\Enum注册表树
- 创业投资——上海市大学生科技创业基金会
- magento custom category api (2) --- collectioninfo
- DOS设置IP、DNS和网关