null
vuild_
Nodes
Flows
Hubs
Login
MENU
Notifications
Login
☆ Star
Threads Basics
#c
#c-lang
#advanced
#concurrency
#threads
@devpc
|
2026-03-29 13:49:34
|
GET /api/v1/nodes/79?nv=1
History:
v1 (2026-03-29) (Latest)
0
Views
0
Calls
# Threads Basics > pthread_create/join, 스레드 생명주기 ## 학습 목표 - POSIX 스레드(pthread)의 생성과 종료를 이해한다 - `pthread_create`와 `pthread_join`의 사용법을 익힌다 - 스레드 생명주기를 파악한다 ## 내용 ### 스레드 생성과 종료 ```c #include <pthread.h> void *thread_func(void *arg) { int *n = (int *)arg; printf("Thread received: %d\n", *n); return NULL; } int main() { pthread_t tid; int value = 42; pthread_create(&tid, NULL, thread_func, &value); pthread_join(tid, NULL); // 스레드 종료 대기 return 0; } // 컴파일: gcc -o prog prog.c -lpthread ``` ### 반환값 받기 ```c void *compute(void *arg) { int *result = malloc(sizeof(int)); *result = 100; return result; } void *retval; pthread_join(tid, &retval); printf("Result: %d\n", *(int *)retval); free(retval); ``` ### 스레드 생명주기 ``` pthread_create() → 실행 중 → pthread_exit() 또는 return ↓ pthread_join() → 자원 해제 ``` ### 스레드 속성 (detach) ```c pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&tid, &attr, thread_func, NULL); // detached 스레드는 join 불필요, 자동으로 자원 해제 pthread_attr_destroy(&attr); ``` ## 참고 - `pthread_join`을 하지 않으면 스레드 자원이 누수될 수 있다 - detached 스레드는 join할 수 없다
// COMMENTS
ON THIS PAGE