MY IT

pthread_join과 pthread_detach 차이

메롱씨티 배드맨 2007. 11. 12. 10:43

프로세서에 thread를 적용하여 구현할때 pthread_create 이후 이 thread함수의 종료를 기다릴때 주로 pthread_join 함수를 사용합니다.

 

-------------------- Sample.1 start ----------------------
void *t_function(void *ptr)
{
      .........
}

 

void func()
{
     thr_id = pthread_create(&p_thread[1], NULL, t_function, (void *)&b);
     pthread_join(p_thread[0], (void **)&status);
}
-------------------- Sample.1 end ------------------------

 

주로 이런식으로 thread를 띄웁니다.

그러나 쓰레드를 띄우는 함수가 여러개인 경우 문제가 발생합니다.

 

-------------------- Sample.2 start ----------------------
void *t_function(void *ptr)
{
     ........
}

 

void func_1()
{
     thr_id = pthread_create(&p_thread[1], NULL, t_function, (void *)&b);
     pthread_join(p_thread[0], (void **)&status);
}

 

void func_2()
{
     thr_id = pthread_create(&p_thread[2], NULL, t_function, (void *)&b);
     pthread_join(p_thread[0], (void **)&status);
}

 

int main()
{
     func_1();
     func_2();

     return 0;
}
-------------------- Sample.2 end ------------------------

 

이렇게 구현했을때, func_1() 함수 내부에 생성한 thread의 종료를 기다리는 pthread_join 함수가 있기 때문에 func_1() 함수는 thread가 종료되기 전에는 끝나지 않고, 따라서 func_2() 함수는 func_1()함수가 끝나기 전까진 실행되지 않습니다.


(물론 func_1() 함수안에다 thread 생성에 관한 모든 루틴을 몰아넣으면 되겠지만, 세상사는게 다 내뜻대로 되는것도 아니고..)

 

이랬을때 func_1()함수에서 thread만 띄우고 종료를 기다리지 않은채 다음 루틴으로 넘어가기 위해서 pthread_detach() 함수를 적용합니다.

 

-------------------- Sample.3 start ----------------------
void *t_function(void *ptr)
{
     pthread_detach(pthread_self());
}

 

void func_1()
{
     thr_id = pthread_create(&p_thread[1], NULL, t_function, (void *)&b);
}

 

void func_2()
{
     thr_id = pthread_create(&p_thread[2], NULL, t_function, (void *)&b);
}

 

int main()
{
     func_1();
     func_2();

     sleep(30);

 

     return 0;
}
-------------------- Sample.3 end ------------------------

 

위의 예제에서 처럼 t_function 함수내의 pthread_detach() 함수를 사용하면 thread를 생성한 parent 함수에서 기다릴 필요가 없습니다.


그러나 메인 프로세서가 종료되면 모든 쓰레드 프로세서도 종료되어 버리기 때문에 메인 프로세서는 유지해줘야 합니다.

'MY IT' 카테고리의 다른 글

Libwww compile option  (0) 2007.12.26
D 프로그래밍 언어  (0) 2007.12.13
Vim 6.x 설정  (0) 2007.10.31
C++ Framework ACE  (0) 2007.08.24
[PHP] 단순 무식 데이터 encoding, decoding   (0) 2007.01.25