C++中Semaphore內查對象用法實例。本站提示廣大學習愛好者:(C++中Semaphore內查對象用法實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C++中Semaphore內查對象用法實例正文
本文實例講述了C++中Semaphore內查對象的用法,分享給年夜家供年夜家參考。詳細辦法以下:
// Semaphore.cpp : 界說掌握台運用法式的進口點。
//
#include "stdafx.h"
#include <Windows.h>
#include <process.h>
HANDLE g_hSemaphore;
DWORD g_nConut1 = 0;
DWORD g_nConut2 = 0;
unsigned __stdcall ThreadProc1( void* pArguments )
{
::WaitForSingleObject(g_hSemaphore, INFINITE);
for (int i=0;i<10000;i++)
{
g_nConut1++;
g_nConut2++;
}
::ReleaseSemaphore(g_hSemaphore, 1, NULL);
printf("ThreadProc1\n");
return 0;
}
unsigned __stdcall ThreadProc2( void* pArguments )
{
::WaitForSingleObject(g_hSemaphore, INFINITE);
for (int i=0;i<10000;i++)
{
g_nConut1++;
g_nConut2++;
}
::ReleaseSemaphore(g_hSemaphore, 1, NULL);
printf("ThreadProc2\n");
return 0;
}
unsigned __stdcall ThreadProc3( void* pArguments )
{
::WaitForSingleObject(g_hSemaphore, INFINITE);
for (int i=0;i<10000;i++)
{
g_nConut1++;
g_nConut2++;
}
::ReleaseSemaphore(g_hSemaphore, 1, NULL);
printf("ThreadProc3\n");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
g_hSemaphore = ::CreateSemaphore(NULL, 2, 2, NULL);
HANDLE hThread[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("main finished.\n");
return 0;
}
願望本文所述對年夜家的C++法式設計有所贊助。