windows多线程分析——Semaphore(信号量)

Semaphore相当于升级版的Mutex,因为当CreateSemaphore(NULL,1,1,NULL)中第三个参数为1时,就相当于是在CreateMutex()。

看一个CreateSemaphore(NULL,1,1,NULL)的实例:

#include <iostream>
#include <Windows.h>
using namespace std;
HANDLE g_hSemaphore=NULL;
unsigned long WINAPI Func(LPVOID IpParamter)
{
	int iRunTime=0;
	while (++iRunTime<100)
	{
		WaitForSingleObject(g_hSemaphore,INFINITE);//如果有Semaphore空闲,才会返回并执行下面程序,否则Blocking
		cout<<"Func() if running"<<endl;
		ReleaseSemaphore(g_hSemaphore,1,NULL);
		Sleep(10);
	}
	ExitThread(-1);
}
int main()
{
	g_hSemaphore=CreateSemaphore(NULL,1,1,NULL);
	if (g_hSemaphore==NULL)
	{
		cout<<"create hSemaphore failed! error_code:"<<GetLastError()<<endl;
		return 0;
	}
	int iRunTime=0;
	unsigned long ulThreadId=0;
	HANDLE hThread=CreateThread(NULL,0,Func,NULL,0,&ulThreadId);
	while (++iRunTime<100)
	{
		WaitForSingleObject(g_hSemaphore,INFINITE);
		cout<<"main() if running,Thread id is"<<ulThreadId<<endl;
		ReleaseSemaphore(g_hSemaphore,1,NULL);
		Sleep(10);
	}
	system("pause");
	return 0;
}

执行结果:


上面的结果和使用Mutex的效果是一样的。

如果改成CreateSemaphore(NULL,2,2,NULL);

效果如下:


可以发现两个线程的执行顺序是无序混乱的,因为他们在互相争抢资源。

猜你喜欢

转载自blog.csdn.net/qq_30483585/article/details/79564712
今日推荐