-
SemaphoreOperations Dev/writech 2010. 12. 10. 18:23
// Example03_Semaphore.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//#include "stdafx.h"
#include<windows.h>
#include<process.h>#include<string>
#include<iostream>
using namespace std;unsigned int WINAPI writeCharacter(LPVOID param);
string g_string;
int const MAX_THREAD = 5;
HANDLE g_semaphoreHandle;int _tmain(int argc, _TCHAR* argv[])
{
g_semaphoreHandle = ::CreateSemaphore(NULL,1, 1 , NULL);
g_string.reserve(MAX_THREAD * 1000 +1); //가용공간 예약부분DWORD threadIDs[MAX_THREAD];
HANDLE threadHandles[MAX_THREAD];
char alphas[MAX_THREAD];for(int i =0; i<MAX_THREAD; ++i)
{
alphas[i] = 'a' + i;threadHandles[i] = (HANDLE) ::_beginthreadex( NULL, 0 , writeCharacter,(LPVOID*)(&alphas[i]),0,(unsigned int *)&threadIDs[i]);
}
DWORD result = ::WaitForMultipleObjects(MAX_THREAD, &threadHandles[0],TRUE,INFINITE);
if(result == WAIT_OBJECT_0)
{
cout<<g_string;
}for(int i = 0; i< MAX_THREAD; ++i)
{
CloseHandle(threadHandles[i]);
}
CloseHandle(g_semaphoreHandle);return 0;
}unsigned int WINAPI writeCharacter(LPVOID param)
{
char ch = *((char *)param);
DWORD result = ::WaitForSingleObject(g_semaphoreHandle,INFINITE);
for(int i = 0; i< 1000; ++i)
{
g_string += ch;
}
::ReleaseSemaphore(g_semaphoreHandle,1,NULL);
return 0;
}
'Operations Dev > writech' 카테고리의 다른 글
Mutex (0) 2010.12.10 CriticalSection (0) 2010.12.10 SpinLock (0) 2010.12.10 SpinLock2 (0) 2010.12.10 SimpleConcurrency (0) 2010.12.10