std::async 似乎没有使用 std::launch::async 生成线程

std::async doesn't seem to spawn thread with std::launch::async

本文关键字:std async launch 线程      更新时间:2023-10-16

我正在编写一个DCPU-16模拟器,我正在通过启动一个线程来计算CPU的实时时钟速度,该线程在单独的线程中调用函数getRealTimeCPUClock()。 问题是,即使 future 对象的"valid"属性没有返回值,它似乎也是真的。 因此,当调用 futureObj.get() 时,它会等待 getRealTimeCPUClock() 返回。

使用异步(而不是延迟)的启动策略,它不应该在后台启动函数,然后在返回时将有效属性设置为 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(); 
    }
}

valid()并没有你认为的那样(尽管cpp首选项中的条目表明并非如此)。

以下是标准对valid()的规定:

(§ 30.6.6/18) bool valid() const noexcept;

返回:仅当 *这是指共享状态时,才为 true。

只要future对象与有效的共享状态相关联,valid()返回的值就会被true,这通常是在使用std::async启动它之后和检索结果之前(使用 get() )。当您使用 share() 方法创建shared_future时,future也将失效。这些都与您尝试执行的操作无关,即检查结果是否可用。

为了确定future的结果是否准备就绪,我建议使用延迟为 0 的 wait_for() 函数:

if (futureRealTimeClockSpeed.wait_for(std::chrono::seconds(0))
          == std::future_status::ready)
   /*...*/