waitforsingleobject使用案例
时间: 2023-06-28 12:03:44 浏览: 189
WaitForSingleObject 是 Windows 操作系统中的一个函数,用于等待一个对象的信号状态。下面是一个使用案例:
```c++
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
if (hMutex == NULL)
{
cerr << "CreateMutex failed with error " << GetLastError() << endl;
return 1;
}
DWORD dwResult = WaitForSingleObject(hMutex, INFINITE);
switch (dwResult)
{
case WAIT_OBJECT_0:
cout << "The object is signaled" << endl;
break;
case WAIT_ABANDONED:
cout << "The object is abandoned" << endl;
break;
case WAIT_TIMEOUT:
cout << "The object is timed out" << endl;
break;
case WAIT_FAILED:
cerr << "WaitForSingleObject failed with error " << GetLastError() << endl;
break;
default:
cerr << "Unknown result " << dwResult << endl;
break;
}
ReleaseMutex(hMutex);
CloseHandle(hMutex);
return 0;
}
```
在上面的代码中,首先使用 CreateMutex 函数创建了一个互斥体对象,并使用 WaitForSingleObject 函数等待该对象的信号状态。在等待期间,函数将被阻塞,直到对象被信号激活或超时。如果对象被激活,则输出 "The object is signaled",如果对象被遗弃,则输出 "The object is abandoned",如果超时,则输出 "The object is timed out"。如果函数失败,则输出相应的错误信息。
最后,使用 ReleaseMutex 函数释放互斥体对象,并使用 CloseHandle 函数关闭对象句柄。
阅读全文