事件可以用来做线程同步
#include <iostream>
#include <Windows.h>
int g_val = 10;
CRITICAL_SECTION cs;
HANDLE event;
DWORD WINAPI SonThreadFunc(LPVOID param)
{
int* num = (int *)param;
std::cout << *num << std::endl;
SetEvent(event);
std::cout << "son thread" << std::endl;
EnterCriticalSection(&cs);
std::cout << g_val++ << std::endl;
LeaveCriticalSection(&cs);
return 0;
}
int main()
{
event = CreateEvent(NULL, FALSE, FALSE, NULL);//第二个参数为FALSE表示自动置位,第三个参数为FALSE表示初始状态为未激发状态
InitializeCriticalSection(&cs);
HANDLE ths[5];
for (size_t i = 0; i < 5; i++)
{
ths[i] = CreateThread(NULL, 0, SonThreadFunc, &i, 0, NULL);
WaitForSingleObject(event, INFINITE);
std::cout << "main thread" << std::endl;
}
WaitForMultipleObjects(5, ths, TRUE, INFINITE);
DeleteCriticalSection(&cs);
for (size_t i = 0; i < 5; i++)
{
CloseHandle(ths[i]);
}
std::cout << "Hello World!\n";
}
该代码示例展示了如何在Windows环境下利用事件对象(event)和临界区(CRITICAL_SECTION)实现线程同步。在5个子线程中,每个线程首先等待事件被触发,然后进入临界区更新全局变量g_val并打印。主线程创建子线程后,等待所有子线程完成,最后释放资源并输出结果。

被折叠的 条评论
为什么被折叠?



