This article illustrates the use of semaphore kernel objects in C + + and share them for everyone's reference. The specific methods are as follows:
Copy Code code as follows:
Semaphore.cpp: Defines the entry point for a console application.
//
#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;
}
I hope this article will help you with the C + + program design.