//多线程同步
//信号量的同步应用
#define WIN32_LEAN_AND_MEAN
#include <STDIO.H>
#include <stdlib.h>
#include <WINDOWS.H>
HANDLE hThread1,hThread2,hThread3;//线程句柄1,线程句柄2,线程句柄3
DWORD ExitCode1,ExitCode2,ExitCode3;//线程1退出码,线程2退出码,线程3退出码
DWORD ThreadId1,ThreadId2,ThreadId3;//线程1的ID,线程2的ID,线程3的ID
//①定义线程句柄
HANDLE hSemaphore;//信号句柄
DWORD WINAPI ThreadFunc(LPVOID);
int main()
{
//②创建Semaphore对象
hSemaphore = CreateSemaphore(
NULL, //默认安全属性
2, //Semaphore的初值,必须大于0并且小于等于下一个变量
4, //Semaphore的最大值
"SemaphoreName" //Semaphore的名子
); //若失败返回NULL,成功返回句柄
hThread1 = CreateThread(NULL,0,ThreadFunc,(LPVOID)1,NULL,&ThreadId1);
hThread2 = CreateThread(NULL,0,ThreadFunc,(LPVOID)2,NULL,&ThreadId2);
hThread3 = CreateThread(NULL,0,ThreadFunc,(LPVOID)3,NULL,&ThreadId3);
GetExitCodeThread(hThread1,&ExitCode1);
GetExitCodeThread(hThread2,&ExitCode2);
GetExitCodeThread(hThread3,&ExitCode3);
Sleep(4000);
printf("线程1的ID = %ld,退出码 = %ld\n",ThreadId1,ExitCode1);
printf("线程2的ID = %ld,退出码 = %ld\n",ThreadId2,ExitCode2);
printf("线程3的ID = %ld,退出码 = %ld\n",ThreadId3,ExitCode3);
//⑤关闭句柄
CloseHandle(hSemaphore);
CloseHandle(hThread1);
CloseHandle(hThread2);
CloseHandle(hThread3);
return 0;
}
DWORD WINAPI ThreadFunc(LPVOID n)
{
//③等待Semaphore对象资源锁定
WaitForSingleObject(hSemaphore,INFINITE);
printf("线程%ld正在运行\n",int(n));
long PreSemaphore;
//④释放资源锁定,解锁
ReleaseSemaphore( //解除锁定
hSemaphore, //Semaphore句柄
1, //现值的增额
&PreSemaphore //传回Semaphore的原值
);
printf("线程%ld返回的原Semaphore是%ld\n",int(n),PreSemaphore);
return (int)n;
}