Do You Coding?
[function] pthread_detach ํจ์ ์์๋ณด๊ธฐ ๋ณธ๋ฌธ

๐ ๋งค๋ด์ผ (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ํด์ค๋ค.
'CS & Engineering > 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 |
| [library] itoa ๊ตฌํํ๊ธฐ (0) | 2024.06.29 |