2014. 6. 13. 11:36

* pthread_create

 헤더

 #include  <pthread.h>

 원형

 int pthread_create(pthread_t * thread, const pthread_attr_t *attr,

     void* (*start_routine)(void*), void *arg);

 인자

 첫번째 : 생성된 스레드의 ID를 저장할 변수의 포인터 옴

 두번째 : 스레드 특징을 설정할때 사용됨, 주로 NULL이 옴

 세번째 : 스레드가 생성되고 나서 실행될 함수가 옴

 네번째 : 세번째 인자에서 호출될 함수에 전달하고자 하는 인자의 값


* pthread_join

 헤더

 #include <pthread.h>

 

 int pthread_join(pthread_t th, void **thread_return);

 인자설명

 첫번째 : 스레드 ID가 옴. 이 ID가 종료할 때까지 실행을 지연

 두번째 : 스레드 종료시 반환값 받음



정확하지 않은 tip!!

pthread_join의 반환값이 스레드 종료시 반환값인데,

스레드 종료할 때 return 보다는 pthread_exit 를 사용하는 것이 더 좋다!

(void * thr_fn1 을 void thr_fn1 로 잘못썻다가 계속 반환값을 이상한 값으로 받아오는 

 오류가 있었다. 스레드 종료값 넘겨줄 때는 pthread_exit가 더 좋은듯 )



예제코드

#include <pthread.h>

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>



void * thr_fn1(void *arg)

{

    printf("thread 1 returning \n");

    return ((void *) 1);

}


void * thr_fn2(void *arg)

{

    printf("thread 2 exiting \n");

    pthread_exit((void *)2);

}



int main(void)

{

    int err;

    pthread_t tid1, tid2;

    void *tret;


    err = pthread_create(&tid1, NULL, thr_fn1, NULL);

    if (err != 0 )

    {

        printf("can't create thread 1: %s\n", strerror(err));

        exit(err);

    }


    err = pthread_create(&tid2, NULL, thr_fn2, NULL);

    if(err != 0 )

    {

        printf("can't create thread 2 : %s\n", strerror(err));

        exit(err);

    }

    err = pthread_join(tid1, &tret);

    if (err != 0 )

    {

        printf("can't join with thread 1: %s\n", strerror(err));

        exit(err);

    }

    printf("thread 1 exit code %d\n", (int)tret);


    err = pthread_join(tid2, &tret);

    if ( err != 0 )

    {

        printf("can't jon with thread 2: %s\n", strerror(err));

        exit(err);

    }

    printf("thread 2 exit code %d\n", (int)tret);

    exit(0);

}


$ gcc 11-3.c -o 11-3 -lpthread

$ 11-3

thread 1 returning

thread 2 exiting

thread 1 exit code 1

thread 2 exit code 2



* 참고 : 유닉스 고급 프로그래밍 11-3 예제 참고

Posted by Triany