【问题标题】:Dining philosophers using semaphores (BACI)使用信号量 (BACI) 就餐哲学家
【发布时间】:2018-06-02 08:33:03
【问题描述】:

我必须通过使用信号量来解决哲学家就餐问题。在我的代码中,每一位哲学家都在拿一根筷子,其余的都在等待。

我在主函数中仍然有一些错误。你能告诉我如何启动筷子[k]吗?我是BACI的初学者。

binarysem ChopStick[5];
binarysem speak;

void philosopher(int index){
int i,k;
int x;
x=0;
for(i=0;i<k;i++){
    cout << "I am philosopher: " << index << " and i am thinking "<< endl;
    signal(speak);
    if(index % 2 == 0){
        wait(ChopStick[index]);
        wait(ChopStick[(index+1) % 5]);
        }
        else{
        wait(ChopStick[index]);
        wait(ChopStick[(index+1) % 5]);
        }
    x++;
    wait(speak);
    cout <<"I am philosopher: "<< index <<" and i eat: "<< x << "times" << endl;
    signal(speak);
    signal(ChopStick[index]);
    signal(ChopStick[(index+1) % 5]);

main(){
int k;
for(k=0;k<5;k++){
    initialsem(ChopStick[k],1);
    initialsem(speak,1);
    }
cobegin
    {
        philosopher(1); philosopher(2); philosopher(3); philosopher(4); philosopher(5);
    }
}

【问题讨论】:

  • 请分享您遇到的具体错误
  • 我遇到了数组“initialsem 不是‘数组’类型的问题。我不知道如何启动它。

标签: concurrency dining-philosopher


【解决方案1】:

根据this BACI summary,听起来数组应该像在 C 中一样初始化。所以你会想要这样的东西:

binarysem initialsem[5];

(其中5是数组的长度,binarysem是数组元素的数据类型)

【讨论】:

    猜你喜欢
    • 2011-07-09
    • 1970-01-01
    • 2018-01-21
    • 2017-04-04
    • 2010-10-11
    • 2016-03-04
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多