我正在编写一个DCPU-16模拟器,并且正在通过启动一个线程来计算CPU的实时时钟速度,该线程在一个单独的线程中调用函数getRealTimeCPUClock()。问题是,即使没有返回值,未来对象的"valid“属性似乎也是真的。因此,当调用futureObj.get()时,它会等待getRealTimeCPUClock()返回。
使用异步(而不是延迟)的启动策略,它不是应该在后台启动函数,然后在它返回时将valid属性设置为true吗?
这是错误的用法吗?
int getRealTimeCPUClock() {
int cyclesBeforeTimer = totalCycles;
sleep(1);
return totalCycles - cyclesBeforeTimer;
}
void startExecutionOfProgram(char *programFileName)
{
size_t lengthOfProgramInWords = loadProgramIntoRAM(programFileName);
auto futureRealTimeClockSpeed = std::async(std::launch::async, getRealTimeCPUClock);
while(programCounter < lengthOfProgramInWords) {
if(futureRealTimeClockSpeed.valid()) {
realTimeClockSpeed = futureRealTimeClockSpeed.get();
futureRealTimeClockSpeed = std::async(std::launch::async, getRealTimeCPUClock);
}
step();
}
}发布于 2012-10-10 16:16:41
valid()并不是您所认为的那样(尽管cppreference中的条目表明情况并非如此)。
以下是该标准对valid()的描述
(§30.6.6/18)布尔有效()常量不例外;
返回:仅当*this引用共享状态时才返回true。
只要valid()对象与有效的共享状态相关联,future返回的值就会是true,这通常是在您使用std::async启动它之后,在您检索结果之前(使用get())。当您使用share()方法创建future时,shared_future也将失效。所有这些都与您尝试做的事情无关,例如,检查结果是否可用。
要确定future的结果是否就绪,我建议使用延迟为0的wait_for()函数:
if (futureRealTimeClockSpeed.wait_for(std::chrono::seconds(0))
== std::future_status::ready)
/*...*/https://stackoverflow.com/questions/12811426
复制相似问题