C++中Semaphore内核对象用法实例
本文实例讲述了C++中Semaphore内核对象的用法,分享给大家供大家参考。具体方法如下:
//Semaphore.cpp:定义控制台应用程序的入口点。
//
#include"stdafx.h"
#include<Windows.h>
#include<process.h>
HANDLEg_hSemaphore;
DWORDg_nConut1=0;
DWORDg_nConut2=0;
unsigned__stdcallThreadProc1(void*pArguments)
{
::WaitForSingleObject(g_hSemaphore,INFINITE);
for(inti=0;i<10000;i++)
{
g_nConut1++;
g_nConut2++;
}
::ReleaseSemaphore(g_hSemaphore,1,NULL);
printf("ThreadProc1\n");
return0;
}
unsigned__stdcallThreadProc2(void*pArguments)
{
::WaitForSingleObject(g_hSemaphore,INFINITE);
for(inti=0;i<10000;i++)
{
g_nConut1++;
g_nConut2++;
}
::ReleaseSemaphore(g_hSemaphore,1,NULL);
printf("ThreadProc2\n");
return0;
}
unsigned__stdcallThreadProc3(void*pArguments)
{
::WaitForSingleObject(g_hSemaphore,INFINITE);
for(inti=0;i<10000;i++)
{
g_nConut1++;
g_nConut2++;
}
::ReleaseSemaphore(g_hSemaphore,1,NULL);
printf("ThreadProc3\n");
return0;
}
int_tmain(intargc,_TCHAR*argv[])
{
g_hSemaphore=::CreateSemaphore(NULL,2,2,NULL);
HANDLEhThread[3];
hThread[0]=(HANDLE)::_beginthreadex(NULL,0,ThreadProc1,NULL,0,NULL);
hThread[1]=(HANDLE)::_beginthreadex(NULL,0,ThreadProc2,NULL,0,NULL);
hThread[2]=(HANDLE)::_beginthreadex(NULL,0,ThreadProc3,NULL,0,NULL);
::WaitForMultipleObjects(2,hThread,TRUE,INFINITE);
printf("g_count1=%d\n",g_nConut1);
printf("g_count2=%d\n",g_nConut2);
printf("mainfinished.\n");
return0;
}
希望本文所述对大家的C++程序设计有所帮助。
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便