본문 바로가기

Programming/C&C++

C언어 Thread


.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 폴더를 모두 등록시킨다.


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

  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #define NUM_THREADS     5
  4.  
  5. void *PrintHello(void *threadid)
  6. {
  7.    long tid;
  8.    tid = (long)threadid;
  9.    printf("Hello World! It's me, thread #%ld!\n", tid);
  10.    pthread_exit(NULL);
  11.  
  12.    return;
  13. }
  14.  
  15. int main (int argc, char *argv[])
  16. {
  17.    pthread_t threads[NUM_THREADS];
  18.    int rc;
  19.    long t;
  20.    for(t=0; t<NUM_THREADS; t++){
  21.       printf("In main: creating thread %ld\n", t);
  22.       rc = pthread_create(&threads[t]NULL, PrintHello, (void *)t);
  23.       if (rc){
  24.          printf("ERROR; return code from pthread_create() is %d\n", rc);
  25.          return -1;
  26.       }
  27.    }
  28.    pthread_exit(NULL);
  29. }