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

thread_exit(쓰레드에서 특정 값을 return을 시키자)

by RoJae 2019. 5. 25.


개발 환경

 OS

 Ubuntu 18.04.2

 컴파일러

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




thread_exit(void *value)

value값을 return 시켜준다.

이 return 값은 join의 두번째 인자에서 받아온다.



소스코드


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
39
40
41
42
43
44
45
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
 
 
// thread function
void *thread_function(void * data){
        // Thread가 return할 값
        static int retval = 999;
        int count = *((int *) data);
        int i = 0;
        while(1){
                // if i == 3 => end thread
                if(i == count )
                {
// Thread return
                        pthread_exit((void *&retval);
                }
                printf("Thread Running ... %d : data %d \n", i, count);
                i++;
                sleep(1);
        }
}
 
int main(){
        pthread_t p_thread;
        int thr_id;
        void *tret = NULL;
        int count = 3;
 
        thr_id = pthread_create(&p_thread, NULL, thread_function, (void *&count);
        if(thr_id < 0)
        {
                perror("생성 실패\n");
                exit(0);
        }
        // pthread_join의 두번째 인자 tret에서 받아서
        // thread가 끝날 때 return 받는다
        pthread_join(p_thread, &tret);
 
        // pthread의 반납값 출력
        printf("thread가 반납한 값  %d\n"*((int *) tret));
        return 0;
}
 

cs





실행결과


1
2
3
4
5
6
$ ./pthread_exit 
Thread Running ... 0 : data 3 
Thread Running ... 1 : data 3 
Thread Running ... 2 : data 3 
thread가 반납한 값  999
 
cs

우선 join을 통해서 main 문에서 return 받을 변수를 정해주었고

exit를 통해서 thread가 return 시켜 줄 변수를 결정한다.

그 이후에 다시 join의 두번째 인자가 return값을 받아와

출력이 정상적으로 된 것을 알 수 있다.



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




반응형

댓글