#include <iostream>
#include <Windows.h>
#include <process.h>
int test_int = 0;
void ThreadLoop(int number)
{
static int thread_number;
std::cout << "(Before)Thread One Test Int : " << thread_number << std::endl;
for(int i = 0; i < number; ++i)
{
std::cout << "Thread For : " << thread_number++ << std::endl;
}
std::cout << "(After)Thread One Test Int : " << thread_number << std::endl;
}
unsigned int WINAPI Thread_Function(void *avg)
{
ThreadLoop(500);
return test_int;
}
void main()
{
HANDLE thread_one;
HANDLE thread_two;
DWORD thread_one_id;
DWORD thread_two_id;
std::cout << "Main Test Int : " << test_int << std::endl;
thread_one = (HANDLE)_beginthreadex(NULL, 0, Thread_Function, NULL, 0,
(unsigned*)&thread_one_id);
if(thread_one == 0)
{
std::cout << "_beginthreades Error" << std::endl;
}
else
{
std::cout << "Create Thread One" << std::endl;
}
thread_two = (HANDLE)_beginthreadex(NULL, 0, Thread_Function, NULL, 0,
(unsigned*)&thread_two_id);
if(thread_two == 0)
{
std::cout << "_beginthreades Error" << std::endl;
}
else
{
std::cout << "Create Thread Two" << std::endl;
}
Sleep(3000);
std::cout << "Main Test Int : " << test_int << std::endl;
std::cout << "Main Exit" << std::endl;
}
위의 코드는 문제가 발생할 만한 코드이다.
500개던지 몇 개를 하였을 때 멀티쓰레드에서 같은 전역 변수를 참조하였을 때
데이터를 중복 사용하여 결과가 다르게 나올 수 있다.
아래 스샷과 같이 원래는 1000이 나와야 하지만 999가 나온 것을 볼 수 있다.
'Programming > C++' 카테고리의 다른 글
쓰레드 동기화 기법 Interlocked (0) | 2013.02.27 |
---|---|
Critical_Section 예제 (0) | 2013.02.20 |
_beginthreadex() 예제 (0) | 2012.11.22 |