Windows多线程-事件

该代码示例展示了如何在Windows环境下利用事件对象(event)和临界区(CRITICAL_SECTION)实现线程同步。在5个子线程中,每个线程首先等待事件被触发,然后进入临界区更新全局变量g_val并打印。主线程创建子线程后,等待所有子线程完成,最后释放资源并输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

事件可以用来做线程同步

#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";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值