C++ Windows MFC 并发:让线程等待,直到达到特定状态
C++ Windows MFC Concurrency: Get thread to wait until particular state achieved
在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
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 如何让LLDB在成功时退出,在失败时等待
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- OSX MetalKit CVMetalTextureCacheCreateTextureFromImage失败,状态:
- std::future_error:无关联状态
- 等待整个 omp 块完成,然后再调用第二个函数
- 如何避免LED在循环状态变化中闪烁?
- boost 是否有按特殊类型值编码状态"compact optional"?
- 提升 ASIO - io_service 不要等待连接到线程
- 如何在C++中实现带有packaged_task的异步等待循环?
- 为什么系统函数总是在C++中返回已转移的退出状态?
- recvfrom 只收到几个数据包,之后它进入等待状态
- Linux进程等待I/O,其状态为S
- 线程池卡在等待状态
- 进程进入wait_blocked状态 500 毫秒.如何找出它正在等待的资源
- 由于从客户端启动守护程序应用程序,服务器端口无法返回侦听并处于关闭等待状态
- 导致c++ 11 std::互斥锁将被阻塞的线程锁定到被动等待状态
- C++ Windows MFC 并发:让线程等待,直到达到特定状态
- 将等待多个对象修改*多个*对象的状态