📌 매뉴얼 (Linux)
NAME
pthread_detach - detach a thread
SYNOPSIS
#include <pthread.h>
int pthread_detach(pthread_t thread);
Compile and link with -pthread.
DESCRIPTION
The pthread_detach() function marks the thread identified by thread as detached.
When a detached thread terminates, its resources are automatically released back to the system
without the need for another thread to join with the terminated thread.
Attempting to detach an already detached thread results in unspecified behavior.
RETURN VALUE
On success, pthread_detach() returns 0; on error, it returns an error number.
ERRORS
EINVAL thread is not a joinable thread.
ESRCH No thread with the ID thread could be found.
📌 함수 설명
이전에 pthread 함수들을 통해 스레드를 만들고 기다리게 했다면, 이번에는 분리해주도록 하겠다.
pthread_detach 함수는 말그대로 특정 스레드를 분리(detach) 상태로 설정하여 해당 스레드가 종료될 때 자동으로
그 자원을 해제하도록 한다. 이를 통해 메인 스레드나 다른 스레드에서 해당 스레드의 종료를 기다리지 않고도
자원 누수를 방지할 수 있다.
int pthread_detach(pthread_t thread);
기본형은 다음과 같다. 매개변수는 분리하고자 하는 스레드의 식별자이고, 반환 값은 int 형으로 오류 코드(errno)이다.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *thread_func(void *arg)
{
int i = *((int*) arg);
int c = *((int*) arg) + 5;
while(i <= c)
{
sleep(1);
printf("running thread %d\n", i);
i ++;
}
return (NULL);
}
int main() {
pthread_t thread;
int result;
int arg = 0;
result = pthread_create(&thread, NULL, thread_func, (void *)&arg);
if (result != 0) {
perror("pthread_create 실패");
return -1;
}
result = pthread_detach(thread);
if (result != 0) {
perror("pthread_detach 실패");
return -1;
}
printf("main running...\n");
pthread_exit(NULL);
}
출력 - std_output)
위의 예시를 보자. 저번 게시글에서 쓰인 thread_func를 똑같이 create 해줬고,
해당 create한 스레드를 pthread_detach로 분리해주었다.
그럼 이제 만들어진 스레드는 main 스레드와 분리된 상태가 되어,
스레드가 종료되면 자동으로 자원이 해제 되므로 pthread_join을 호출할 필요가 없다.
만약, 위 상황에서 pthread_detach()를 호출하지 않은 경우, 스레드가 종료되더라도 자원이 해제되지 않는다.
반드시 pthread_join()을 호출하여 스레드가 사용한 자원을 해제해야 하며,
pthread_join()을 호출하지 않으면 메모리 누수가 발생할 수 있다.
(코드에서 pthread_exit(NULL)을 사용했는데 이는 특정 스레드만 종료시키고 다른 스레드들은 계속
실행하고자할 때 사용하는데, 보통 메인 함수에서 다른 스레드들이 작업을 완료할 시간을 주기위해 사용한다.)
pthread_join 과 pthread_detach 두 함수 모두 스레드가 종료하면 자원을 free해주는데,
pthread_join은 반환값을 받아와 또 다른 제어를 한다면,
pthread_detach는 제어 없이 바로 할당된 메모리를 free해준다.
'프로그래밍 > C' 카테고리의 다른 글
[library] atoi 구현하기 (0) | 2025.03.12 |
---|---|
[function] pthread_join 함수 알아보기 (8) | 2024.09.07 |
[function] pthread_create 함수 알아보기 (5) | 2024.09.07 |
[utility] get_next_line 구현하기 (3) | 2024.08.31 |
[graphic] miniLibX Manual (0) | 2024.08.06 |