1

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

3 回答 3

4

CEvent 类

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

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

让我们来说明一下:

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;
    }
}
于 2013-01-29T11:05:14.637 回答
2

您要使用的是事件对象。

于 2013-01-29T06:20:25.797 回答
2

您可以使用 WinAPI 代替轮询:请参阅CreateEventWaitForSingleObject

于 2013-01-29T06:20:52.380 回答