gpt4 book ai didi

c++ - Dining philosophers 和 mutex 初始化

转载 作者:行者123 更新时间:2023-11-28 07:37:01 31 4
gpt4 key购买 nike

我正在尝试解决哲学家用餐问题。所以我几乎编写了整个代码,但问题是我无法初始化监视器(我制作了我用 C++ 重写的伪代码)所以我真的不能测试程序。谁能帮我说说 monitor/mutex_init 的初始化有什么问题?

我在第 18 行遇到错误,它是这样的: 错误:“int pthread_mutex_init”重新声明为不同类型的符号

将其更改为 int pthread_mutex_init(&monitor,NULL); 不会工作!

通过添加int pthread_mutex_init(pthread_mutex_t *monitor, NULL);

我收到错误:‘__null’之前的预期标识符

#include <iostream>
#include <cstdio>
#include <pthread.h>
#include <cstdlib>
#include <unistd.h>

using namespace std;


char v_filozofi[5]={'O'}; //vizualni prikaz filozofa
int stapic[5]={1}; //stapici za filozofe
int broj[5]; //shema koju sam mora sloziti da imam broj filozofa

pthread_t d_filozofi[5]; //dretve filozofa,philosopher's thread
pthread_cond_t red_uvjeta[5];
pthread_mutex_t monitor; //deklariramo monitor,tj mymutex

int pthread_mutex_init(*monitor,NULL);

void ispisi_stanje(int n){
for(int i = 0; i < 5 ;i++) cout<< v_filozofi[i];
cout<<"("<< n+1 << ")" <<endl;
}

void misliti(int n){
cout<<"Mislim " << endl;
sleep(4);
}

void jesti(int n){
pthread_mutex_lock(&monitor);
v_filozofi[n]='o';
while(stapic[n]==0 || stapic[n+1]%5==0){//gleda ima li lijevi i desni
//stapic na raspolaganju
pthread_cond_wait(&red_uvjeta[n],&monitor);
}
stapic[n] = stapic[(n+1)%5] = 0;
v_filozofi[n] = 'X';

ispisi_stanje(n);

pthread_mutex_unlock(&monitor);
sleep(2);
pthread_mutex_lock(&monitor);
v_filozofi[n] = 'O';

stapic[n] = stapic[(n+1)%5] = 1;

pthread_cond_signal(&red_uvjeta[(n-1)%5]);
pthread_cond_signal(&red_uvjeta[(n+1)%5]);

ispisi_stanje(n);
pthread_mutex_unlock(&monitor);


}

void * filozof(void *n){
int br_fil = *((int *)n);
while(1){
misliti(br_fil);
jesti(br_fil);
}
return 0;
}

//MAIN
int main(){
for(int i=0;i<5;i++){
broj[i] = i;
pthread_cond_init(&red_uvjeta[i],NULL);
}
for(int i=0;i<5;i++){
sleep(1);
pthread_create( &d_filozofi[i],NULL,filozof,&broj[i]);
}

for(int i=0;i<5;i++) pthread_join(d_filozofi[i],NULL);
pthread_mutex_destroy(&monitor);

return 0;
}

最佳答案

删除行

int pthread_mutex_init(*monitor,NULL);

而是做

pthread_mutex_init(&monitor,NULL); 

在主函数的开头。 (并检查它是否返回 0)

实际上你是在声明函数而不是调用它,因为它已经被声明了所以你得到了一个错误

关于c++ - Dining philosophers 和 mutex 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16608232/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com