首页 > 解决方案 > 在给定的时间后调用另一个无效

问题描述

我想在给定时间后调用另一个 void。我的代码不起作用:

void Philosopher::think()
{
    auto start = chrono::system_clock::now();
    cout<<"Philosopher nr: "<<id<<" is thinking"<<endl;
    if (chrono::system_clock::now()-start == think_time)
    {
        starve();
    }

}

标签: c++chrono

解决方案


从上下文中很难判断你如何使用你的函数think(),有两种可能性:

  • 你调用它一次,并期望它一直持续到当前的哲学家完成思考。你可以这样编程:
void Philosopher::think()
{
    cout<<"Philosopher nr: "<<id<<" is thinking"<<endl;
    while (chrono::system_clock::now()-start < think_time)
    { 
        // do nothing in this loop, just wait
    }
    starve();
}
  • 在您展示的代码之外,您遍历哲学家并调用此方法,该方法需要starve()那些已经思考过的人。为此,您可以例如在Philosopher课堂上创建另一个字段,开始思考时间,然后反复检查每个哲学家的状态:
void Philosopher::think()
{
    cout<<"Philosopher nr: "<<id<<" is thinking"<<endl;
    if (chrono::system_clock::now()-this.think_start >= think_time)
    {
        starve();
    }
}

int main() 
{
    // ... some code
    auto start = chrono::system_clock::now();
    for(auto philosopher : philosophers)
    {
        philosopher.think_start = start  
    }
    while(/* some condition to stop checking philosophers' state */) 
    {
        for(auto philosopher : philosophers)
        {
            philosopher.think()
        }
    }
    
    // ... some code
}

推荐阅读