본문 바로가기
C_C++ 프로그래밍

pthread_join(쓰레드의 종료를 대기한다)

by RoJae 2019. 5. 25.


개발 환경

 OS

 Ubuntu 18.04.2

 컴파일러

 gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04)




pthread_join(pthread_t thread, void ** return);

(thread가 종료하기를 기다리다가 종료하면

포인터를 리턴한다.)


첫번째 인자 : thread 객체

두번째 인자 : NULL이 아니면 포인터 값을 return 받을 수 있다.



소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
 
// thread_function
// 1초를 기다린 이후
// 매개변수 * 매개변수를 return 한다.
void *thread_function(void *data){
        int num = *((int *) data);
        printf("Num : %d \n", num);
        sleep(1);
        num *= num;
        printf("thread function end\n");
        return (void *)(num);
}
 
int main(){
        pthread_t p_thread;
        int thr_id;
        int result;
        int a = 200;
        thr_id = pthread_create(&p_thread, NULL, thread_function, (void *&a);
        if(thr_id < 0){
                perror("thread create error");
                exit(0);
        }
 
        // 쓰레드 식별자 p_thread가 종료되길 기다렸다가
        // 종료 후에 리턴 값을 받아온다.
        pthread_join(p_thread, (void *&result);
        printf("thread join : %d\n", result);
 
        printf("Main() 종료 \n");
 
        return 0;
}
 
cs



실행결과

1
2
3
4
5
read_join 
Num : 200 
thread function end
thread join : 40000
Main() 종료 
cs




※ 본 글은 개인 포트폴리오 혹은 공부용으로 사용하기 때문에, 무단 복사 유포는 금지하지만, 개인 공부 용도로는 얼마든지 사용하셔도 좋습니다


댓글