windows C++ 用信号量控制线程

时间:2022-11-16 18:26:54

控制信号量几个主要的函数:

WaitForSingleObject();//等待信号量有效 
CreatSemaphore(); //申请信号量  
OpenSemaphore(); //打开信号量  
ReleaseSemaphore(); //释放信号量
函数原型:
1.创建
HANDLE ghSemaphore = CreateSemaphore(
                                            NULL,// default security attributes - lpSemaphoreAttributes是信号量的安全属性
                                            MAX_SEM_COUNT, // initial count - lInitialCount是初始化的信号量
                                            MAX_SEM_COUNT, // maximum count - lMaximumCount是允许信号量增加到最大值
                                            NULL);// unnamed semaphore - lpName是信号量的名称 
2.关闭
CloseHandle(ghSemaphore);//handle to semaphore - hSemaphore关闭信号量句柄
3.释放信号量
ReleaseSemaphore(
          ghSemaphore, // handle to semaphore - hSemaphore是要增加的信号量句柄
          1, // increase count by one - lReleaseCount是增加的计数
          NULL)// not interested in previous count - lpPreviousCount是增加前的数值返回
4.等待信号量有效
DWORD dwWaitResult= WaitForSingleObject(
                                            
ghSemaphore,// handle to semaphore
                                            
0Lor INFINIATE));// zero-second time-out interval