在 Windows MFC 并发上,我如何告诉我当前的线程等到达到特定状态?目前我能想到的唯一方法是执行定期睡眠并检查状态——当我们处于预期状态时,然后继续。有没有更好的方法来做到这一点?
BOOL achieved = FALSE;
int main (int argc, char** argv) {
// This function creates a new thread and modifies the 'achieved' global variable at some point in the future
doSomethingOnAnotherThread();
// Wait maximum 4 seconds for 'achieved' to be TRUE, otherwise give up
for(int i=0; i<5; i++) {
EnterCriticalSection(&CS);
int localAchieved = achieved;
LeaveCriticalSection(&CS);
if (!localAchieved) {
if(i==4) {
cout << "waited too long .. giving up" << endl;
break;
}
Sleep(1000); // let's wait 1 more second and see what happen
} else {
cout << "achieved is TRUE, resuming main thread" << endl;
break;
}
}
}