C++におけるSemaphoreカーネルオブジェクトの使用例
2404 ワード
この例では、C++のSemaphoreカーネルオブジェクトの使い方を説明し、参考にしてください.具体的な方法は以下の通りです.
本稿で述べたことが皆さんのC++プログラム設計に役立つことを願っています.
// Semaphore.cpp : 。
//
#include "stdafx.h"
#include
#include
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
");
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
");
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
");
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
", g_nConut1);
printf("g_count2=%d
", g_nConut2);
printf("main finished.
");
return 0;
}
本稿で述べたことが皆さんのC++プログラム設計に役立つことを願っています.