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():The value returned by
valid()will betrueas long as long as thefutureobject is associated with a valid shared state, which is generally the case after you launched it usingstd::asyncand before you retrieve the result (usingget()). Thefuturewill also be invalidated when you use theshare()method to create ashared_future. None of this is related to what you are trying to do, i.e. checking whether the result is available.To determine whether the result of a
futureis ready, I suggest using thewait_for()function with a delay of 0: