detach를 통한 스레드 반환

2019. 7. 26. 09:29임베디드/리눅스시스템프로그래밍

스레드 생성 전에 스레드 PTHREAD_CREATE_DETACHED 속성을 줘서 자원을 알아서 반환하도록 설정할 수 있다. detach를 사용하면 pthread_join으로 스레드 종료를 대기하지 않아도 스스로 스레드가 반환할 수 있도록 설정할 수 있다

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
void *thread_main(void *arg) {
for(int i=0; i<5; i++) {
printf("Running time : %d\n", i+1);
sleep(1);
}
printf("thread main exit\n");
return NULL;
}
int main(int argc, char **argv)
{
pthread_t tid;
pthread_attr_t attr;
int state;
if(pthread_attr_init(&attr) != 0) {
return -1;
}
if(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) {
return -1;
}
if(pthread_attr_getdetachstate(&attr, &state) != 0) {
return -1;
}
printf("pthread_attr_getdetachstate : %d\n", state);
if(pthread_create(&tid, &attr, thread_main, NULL) != 0) {
return -1;
}
if(pthread_attr_destroy(&attr) != 0) {
return -1;
}
while(1) {
sleep(1);
printf("hello world\n");
}
return 0;
}
#if 0
pthread_attr_getdetachstate : 1
Running time : 1
hello world
Running time : 2
hello world
Running time : 3
hello world
Running time : 4
hello world
Running time : 5
hello world
thread main exit
hello world
hello world
hello world
#endif

 

이외에도 스레드를 생성한 이후에 pthread_detach 함수를 사용해서 위의 detach 속성을 줄 수 있다. 하지만, 스레드를 생성한 후에 속성을 변경한 것이라 코드 흐름상의 문제가 생길 수 있으니 지양하는 것이 좋다

'임베디드 > 리눅스시스템프로그래밍' 카테고리의 다른 글