c++ - 在给定的时间后调用另一个无效
问题描述
我想在给定时间后调用另一个 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();
}
}
解决方案
从上下文中很难判断你如何使用你的函数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
}
推荐阅读
- macos - 以编程方式设置 NSWindow 大小不起作用
- npm - 在内置的自创反应模块中获取重复功能
- javascript - 将数组中的附加值添加到工具提示
- excel - 如何使用 VBA 在 Excel 文件中设置 Sharepoint 文档类型?
- android - 无法使用 Google vision api 扫描条形码
- google-drive-api - 如何使用 wget 下载 Google Drive 文件夹?
- angular - 更新模型后,Angular 单元测试访问由 *ngif 调节的组件的 DOM 元素
- php - Woocommerce:更新所有产品的功能
- java - 选择性地@JsonIgnore Immutables 访问器方法,仅在使用 Jackson 进行序列化或反序列化期间
- node.js - 如何在生产中访问 nodejs 终端以查看运行时错误