#include "stdafx.h"
#include <windows.h>
int g_num = 0;
HANDLE g_hSemaphore = nullptr;
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
for (int i = 0; i < 5;i++)
{
// WaitForSingleObject会自动把g_hSemaphore - 1;
WaitForSingleObject(g_hSemaphore, INFINITE);
printf("%d ", i);
ReleaseSemaphore(g_hSemaphore, 1, NULL);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
if (!(g_hSemaphore = CreateSemaphore(NULL, 0, 2, NULL)))return 0;
HANDLE hHandle[2] = { 0 };
hHandle[0] = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
hHandle[1] = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
// 等待返回
ReleaseSemaphore(g_hSemaphore, 1, NULL);
WaitForMultipleObjects(2, hHandle, TRUE, INFINITE);
system("pause");
return 0;
}
【Windows原理】线程同步-信号量
使用信号量控制并发示例
最新推荐文章于 2022-09-21 21:13:45 发布
本文通过一个C++示例介绍了如何利用Windows API中的信号量(Semaphore)来控制两个线程间的并发执行顺序,确保资源的安全访问。
1217

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



