#include <iostream>
#include <Windows.h>
#include <process.h>
int test_int = 0;
// 크리티컬 섹션 변수
CRITICAL_SECTION critical_section_;
void ThreadLoop(int number)
{
static int thread_number;
for(int i = 0; i < number; ++i)
{
std::cout << "Thread For : " << thread_number++ << std::endl;
}
}
unsigned int WINAPI Thread_Function_One(void *avg)
{
// 크리티컬 섹션 진입
EnterCriticalSection(&critical_section_);
std::cout << "Thread One Start" << std::endl;
ThreadLoop(10);
std::cout << "Thread One End" << std::endl;
// 크리티컬 섹션 나가기
LeaveCriticalSection(&critical_section_);
return test_int;
}
unsigned int WINAPI Thread_Function_Two(void *avg)
{
EnterCriticalSection(&critical_section_);
std::cout << "Thread Two Start" << std::endl;
ThreadLoop(10);
std::cout << "Thread Two End" << std::endl;
LeaveCriticalSection(&critical_section_);
return test_int;
}
void main()
{
HANDLE thread_handle[2];
DWORD thread_one_id;
DWORD thread_two_id;
// 크리티컬 섹션 초기화
InitializeCriticalSection(&critical_section_);
thread_handle[0] = (HANDLE)_beginthreadex(NULL, 0, Thread_Function_One, NULL, 0,
(unsigned*)&thread_one_id);
if(thread_handle[0] == 0)
{
std::cout << "_beginthreades Error" << std::endl;
}
else
{
std::cout << "Create Thread One" << std::endl;
}
thread_handle[1] = (HANDLE)_beginthreadex(NULL, 0, Thread_Function_Two, NULL, 0,
(unsigned*)&thread_two_id);
if(thread_handle[1] == 0)
{
std::cout << "_beginthreades Error" << std::endl;
}
else
{
std::cout << "Create Thread Two" << std::endl;
}
// 두 스레드가 종료 될 때까지 기다린다.
WaitForMultipleObjects(2, thread_handle, TRUE, INFINITE);
std::cout << "Main Exit" << std::endl;
// 크리티컬 섹션 지우기
DeleteCriticalSection(&critical_section_);
}
'Programming > C++' 카테고리의 다른 글
쓰레드 동기화 기법 Interlocked (0) | 2013.02.27 |
---|---|
멀티 쓰레드의 문제 (0) | 2012.11.29 |
_beginthreadex() 예제 (0) | 2012.11.22 |