C++ Windows MFC 并发:让线程等待,直到达到特定状态

C++ Windows MFC Concurrency: Get thread to wait until particular state achieved

本文关键字:状态 等待 MFC Windows 并发 线程 C++      更新时间:2023-10-16

在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;
    }
  }
}

CEvent Class:

表示一个事件,该事件是一个同步对象,它使一个线程能够通知另一个线程发生了事件。

因此,它是解决问题的合适工具。

让我们来说明一下:

void DoSomethingOnAnotherThread(CEvent* event)
{
    // Long-running operation.
    ...
    // Sets the state of the event to signaled, releasing any waiting threads.
    event->SetEvent();
    // TODO: maybe add try/catch and SetEvent() always after the long-running operation???
}
int main (int argc, char** argv)
{
    // Manual-reset event.
    CEvent achieved_event(FALSE, TRUE);
    // This function creates a new thread and modifies the 'achieved' global variable at some point in the future
    DoSomethingOnAnotherThread(&achieved_event);
    // Wait the event to be signalled for 4 seconds!
    DWORD wait_result = WaitForSingleObject(achieved_event, 4000);
    switch (wait_result) {
    case WAIT_OBJECT_0:
        std::cout << "Achieved!" << std::endl;
        break;
    case WAIT_TIMEOUT:
        std::cout << "Timeout!" << std::endl;
        break;
    default: // WAIT_FAILED
        std::cout << "Failed to wait!" << std::endl;
        break;
    }
}

要使用的是事件对象。

您可以使用 WinAPI 代替轮询: 请参阅 CreateEvent 和 WaitForSingleObject