-
pthread_cleanup_pop, pthread_cleanup_pushC_C++ 프로그래밍 2019. 5. 25. 01:42
개발 환경
OS
Ubuntu 18.04.2
컴파일러
gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04)
void pthrad_cleanup_push(void (*routine) (void *), void* arg);
Thread 종료 시 routine 함수가 실행이 됩니다.arg는 넘겨지는 인자 값.cleanup handler 함수는보통 자원을 반납하거나 mutex lock 혹은 unlock을 사용하기 위해서호출됩니다.void pthread_cleanup_pop(int execute);cleanup handler 함수를 제거합니다.매개변수가 0이면 실행하지 않고 삭제하며0이 아니라면 실행한 이후에 삭제됩니다.claenup handler 함수는 자원을 반납하거나, mutex 등의 잠금 해제등을 위한 용도로 사용됩니다. (mutex 에 대한 포스팅은 후에 기회가 닿는대로 하도록 하죠)
출처: https://bitsoul.tistory.com/166?category=683199 [Happy Programmer~]void pthrad_cleanup_push(void (*routine) (void *), void* arg);
출처: https://bitsoul.tistory.com/166?category=683199 [Happy Programmer~]void pthrad_cleanup_push(void (*routine) (void *), void* arg);
출처: https://bitsoul.tistory.com/166?category=683199 [Happy Programmer~]void pthrad_cleanup_push(void (*routine) (void *), void* arg);
출처: https://bitsoul.tistory.com/166?category=683199 [Happy Programmer~]void pthrad_cleanup_push(void (*routine) (void *), void* arg);
출처: https://bitsoul.tistory.com/166?category=683199 [Happy Programmer~]소스코드
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#include<stdio.h>#include<pthread.h>#include<stdlib.h>#include<unistd.h>// clean up handlervoid cleanup(void *arg){printf("Thread Clean up\n");free(arg); // resource free}// thread functionvoid *thread_function(void * data){static int retval = 999;int count = *((int *) data);int i = 0;char *mydata;mydata = (char *) malloc(10000);// pthread_cleanup_push를 걸어 자원을 free 시켜줌pthread_cleanup_push(cleanup, (void *) mydata);while(1){// if i == 3 => end threadif(i == count ){pthread_exit((void *) &retval);}printf("Thread Running ... %d : data %d \n", i, count);i++;sleep(1);}// cleanUp handler를 해제시켜준다.pthread_cleanup_pop(0);}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("thread create error\n");exit(0);}// pthread_join의 두번째 인자 tret에서 받아서// thread가 끝날 때 return 받는다pthread_join(p_thread, &tret);// pthread의 반납값 출력printf("thread exit code %d\n", *((int *) tret));return 0;}cs 실행결과
123456$ ./pthread_cleanupThread Running ... 0 : data 3Thread Running ... 1 : data 3Thread Running ... 2 : data 3Thread Clean upthread exit code 999cs ※ 본 글은 개인 포트폴리오 혹은 공부용으로 사용하기 때문에, 무단 복사 유포는 금지하지만, 개인 공부 용도로는 얼마든지 사용하셔도 좋습니다
반응형'C_C++ 프로그래밍' 카테고리의 다른 글
pthread_mutex_init (뮤텍스 사용하기!) (0) 2019.05.25 pthread_attr 사용 (pthread_detach 없이 자원 반납하기) (0) 2019.05.25 thread_exit(쓰레드에서 특정 값을 return을 시키자) (0) 2019.05.25 pthread_detach(쓰레드 자원들을 분리시키자) (0) 2019.05.25