• 大小: 3KB
    文件类型: .zip
    金币: 1
    下载: 0 次
    发布日期: 2021-06-03
  • 语言: 其他
  • 标签:

资源简介

有三个.cpp文件,代码是我亲手写的,都可以运行,这个代码包含有3种方式避免死锁的方法,一个是允许四个哲学家同时进餐,第二个是一下子就拿两根筷子,否则不拿,第三个就是奇数哲学家先拿左边的筷子,偶数哲学家拿右边的筷子

资源截图

代码片段和文件信息

#include 
#include 
#include 

#define num 4
//静态加载pthreadVC2.lib库文件
#pragma comment(lib “pthreadVC2.lib“)


//声明互斥信号量五根筷子互斥使用
pthread_mutex_t chopstick[5] = { PTHREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
                                 PTHREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER };

//函数声明
void getChop(int i);
void layChop(int i);
void *philosophe(void *i);

//全局变量声明
//用来表示有多少个哲学家在拿筷子
int count =0;

int main()
{
//声明进程变量thread1
pthread_t thread1t1t2t3t4t5;
//创建五个进程
//以此方式创建线程一直都是以顺序执行的,
/* for (int i = 0; i < 5; i++) {
pthread_create(&thread1 NULL philosophe (void*)(i+1));
pthread_join(thread1 NULL);
}*/
pthread_create(&t1 NULL philosophe (void*)1);
pthread_create(&t2 NULL philosophe (void*)2);
pthread_create(&t3 NULL philosophe (void*)3);
pthread_create(&t4 NULL philosophe (void*)4);
pthread_create(&t5 NULL philosophe (void*)5);
pthread_join(t1 NULL);
pthread_join(t2 NULL);
pthread_join(t3 NULL);
pthread_join(t4 NULL);
pthread_join(t5 NULL);
system(“pause“);
return 0;
}

/*
哲学家方法,用于线程的创建
*/
void *philosophe(void *i) {
int index = (int)i;
getChop(index);
printf(“哲学家%d开始进餐!\n“ index);
layChop(index);
return NULL;
}
/*
哲学家拿起筷子的方法
*/
void getChop(int i) {
//当唤醒后,要去判断拿到筷子的人数是否达到四人
while (count<4) {
int ret_trylock1 = pthread_mutex_lock(&chopstick[i-1]);
//当有哲学家拿起第一个筷子的时候就表示有一个人在拿筷子了
if (!ret_trylock1) {
count++;
}
int ret_trylock2 = pthread_mutex_lock(&chopstick[i%5]);

if (!ret_trylock1 && !ret_trylock2) {
break;
}
}
}

//哲学家放筷子开始思考
void layChop(int i)
{
//把打印语句放在上面是考虑到当把锁释放后,会立即有线程对资源进行加锁,以为是程序逻辑有问题
printf(“哲学家%d已经进餐完毕,开始思考\n“ i);

pthread_mutex_unlock(&chopstick[i - 1]);
pthread_mutex_unlock(&chopstick[i % 5]);
                //释放两只筷子资源后就使count-1表示此时吃饭的人减少了一位
count--;
}





 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----
     文件        2211  2019-05-05 20:16  只有四个哲学家吃饭.cpp
     文件        2138  2019-05-05 20:16  同时拿两根筷子.cpp
     文件        1773  2019-05-05 20:16  奇数拿先左边在拿右边.cpp

评论

共有 条评论