简体   繁体   中英

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

I am writing a DCPU-16 emulator and I am calculating the real time clock speed of the CPU by launching a thread that calls the function getRealTimeCPUClock() in a separate thread. The problem is it seems that the future object's "valid" attribute is true even when it has not returned a value. As a result, when calling futureObj.get(), it then waits for getRealTimeCPUClock() to return.

With a launch policy of async (as opposed to deferred) isn't it supposed to launch the function into the background and then when it returns set the valid attribute to true?

Is this the wrong usage?

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() does not what you think it does (although the entry in cppreference suggests otherwise).

Here is what the Standard says about valid() :

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

Returns: true only if *this refers to a shared state.

The value returned by valid() will be true as long as long as the future object is associated with a valid shared state, which is generally the case after you launched it using std::async and before you retrieve the result (using get() ). The future will also be invalidated when you use the share() method to create a shared_future . None of this is related to what you are trying to do, ie checking whether the result is available.

To determine whether the result of a future is ready, I suggest using the wait_for() function with a delay of 0:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM