본문 바로가기

C/Reference

[C] Thread 사용 예제

반응형
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <process.h>
#include <locale.h>

unsigned WINAPI ThreadProc(LPVOID lpParam); // Thread Func 함수 형식이 반드시 이와 같아야 함.

int _tmain(int argc, LPTSTR argv[])
{
	_tsetlocale(LC_ALL, _T("Korean")); // 유니코드에서 한글 출력을 위한 코드

	DWORD dwThreadID[3] = {0};
	HANDLE hThread[3] = {0};

	for(int i = 0; i < 3; i++)
	{
		hThread[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, (LPVOID)i, 0, (unsigned *)&dwThreadID[i]); // Thread 생성

		if(hThread == NULL)
		{
			_tprintf(_T("Thread creation fault!\n"));
			return -1;
		}
	}

	WaitForMultipleObjects(3, hThread, TRUE, INFINITE);

	DWORD retVal = 0;
	GetExitCodeThread(hThread[0], &retVal);
	_tprintf(_T("첫번째 Thread return value[%d]\n"), retVal);

	GetExitCodeThread(hThread[1], &retVal);
	_tprintf(_T("두번째 Thread return value[%d]\n"), retVal);

	GetExitCodeThread(hThread[2], &retVal);
	_tprintf(_T("세번째 Thread return value[%d]\n"), retVal);

	CloseHandle(hThread[0]);
	CloseHandle(hThread[1]);
	CloseHandle(hThread[2]);

	return 0;
}

unsigned WINAPI ThreadProc(LPVOID lpParam)
{
	DWORD num = (DWORD)lpParam;

	for(int i = 0; i < 3; i++)
	{
		_tprintf(_T("Thread Running [%d]\n"), num * i);
		Sleep(3000);
	}

	return num;
}
반응형