Windows API 멀티 쓰레드 구현법

by digipine posted Oct 29, 2017
?

Shortcut

PrevPrev Article

NextNext Article

ESCClose

Larger Font Smaller Font Up Down Go comment Print

멀티스레드

방법

10개의 각각 스레드가 0~1의 숫자를 동시 출력한다.

 

요구사항

1. 스레드함수 만들것

2. 10개 스레드 핸들러 만들것

3. 10개 스레드 종료를 기다리는 메인스레드 코드 추가할 것

 

구현시 발견한점

Sleep(1L)은 0.001초를 다른 스레드 생성까지 기다리는 함수다.

만일 이것이 없을 경우 cout 전역변수를 마구 사용하게 되서

원하는 결과를 얻을 수 없다. cout 전역변수를 크리티컬 섹션으로 지정하던지

아니면 각 스레드에게 Sleep(1L)처럼 약간의 시간간격으로 실행되도록 하는 방법을 써야한다.

( 궁금하면 Sleep(1L)을 지우고 해보세요 )

 

구현소스

#include <windows.h>
#include <process.h>
#include <iostream>

using namespace std;

 

void thread_func(void *arg)
{
 int *th_id = (int*)arg;
 for(int i=0; i<2; i++)
 {
   cout << *th_id << " : " << i << endl << flush;
  }
}


main(void)
{
 int nThreads = 10;
 HANDLE *threads = new HANDLE[nThreads];
 
 for(int i=0; i<nThreads; i++)
 {
  threads[i] = (HANDLE)_beginthread(thread_func,0,&i);
  Sleep(1L);
 }

 WaitForMultipleObjects(nThreads,threads,TRUE,INFINITE);
}
 

TAG •