C++取消Sleep()
时间: 2025-01-05 20:36:09 浏览: 6
### 取消或中断C++中的`Sleep`函数
在多线程环境中,当一个线程调用了 `Sleep` 函数后,该线程会进入阻塞状态一段时间。然而,在某些情况下可能需要提前唤醒这个正在休眠的线程。对于 Windows 平台下的 C++ 编程而言,直接取消 `Sleep` 是不可行的;但是可以通过其他方式实现类似的效果。
一种常见的做法是利用事件对象来代替简单的睡眠操作。通过创建一个手动重置事件并让等待线程监视此事件的状态变化,可以达到灵活控制的目的:
```cpp
#include <windows.h>
#include <iostream>
void ThreadFunction(HANDLE hEvent)
{
while (true)
{
std::cout << "Thread is working..." << std::endl;
// Wait for either timeout or event signal.
DWORD result = WaitForSingleObject(hEvent, 2000); // Replace Sleep(2000)
if (result == WAIT_OBJECT_0)
{
std::cout << "Thread received interruption request." << std::endl;
break; // Exit loop on event set.
}
}
std::cout << "Thread exiting." << std::endl;
}
int main()
{
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
DWORD dwThreadId;
HANDLE hThread = CreateThread(
NULL,
0,
reinterpret_cast<LPTHREAD_START_ROUTINE>(ThreadFunction),
static_cast<LPVOID>(hEvent),
0,
&dwThreadId
);
// Simulate some work before interrupting the thread...
Sleep(5000);
SetEvent(hEvent); // Signal the event to wake up waiting thread.
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
CloseHandle(hEvent);
return 0;
}
```
这种方式不仅能够模拟定时器的行为,而且允许外部逻辑主动触发终止条件[^1]。
阅读全文