학습/프로그래밍

Windows(Win32) - C/C++에서 pthreads 쓰기

TayCleed 2011. 3. 24. 17:45
.Net 기반에서는 using System.Threading; 하고 스레드를 쓰면 된다...

하지만 C/C++ 만 가지고 Win32에서 쓰레드 쓰려다 참 고생 많이 했다..

POSIX 표준 Thread, 줄여서 보통 pthreads라고 불리는 것을 Win32에서 쓰는 법.

1. 일단 http://sourceware.org/pthreads-win32/ 로 가서 DLL, LIB, header 파일을 받는다. 

Just the DLLs, LIBs, header files, and admin documentation is available at:
ftp://sourceware.org/pub/pthreads-win32/dll-latest
  • include 폴더와 lib 폴더를 받으면 된다. 

2. 그리고 다운받은 파일 중 DLL 파일들은 모두 Windows\System32\ 안에 복사해준다. 

3. 그리고 Visual Studio에서. 

 - 프로젝트 -> 속성 -> VC++ 디렉터리로 간다.
 - - 포함 디렉터리 항목에 다운받은 include 폴더를 추가하고, 
 - - 라이브러리 디렉터리 항목에 다운받은 lib 폴더를 추가한다.
 - 프로젝트 -> 속성 -> 링커 -> 입력 -> 추가 종속성 항목에 LIB 파일들을 적어준다.
 - 프로젝트 -> 속성 -> C/C++ -> 일반 -> 추가 포함 디렉터리에 include, lib 폴더를 모두 등록시킨다.


이제 준비 완료다. 프로젝트를 만들고 아래 코드를 컴파일 후 실행하여 테스트 해보자.

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);

   return;
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         return -1;
      }
   }
   pthread_exit(NULL);
}