엔지니어가 되고 싶은 공돌이
09. Thread 본문

9. 1. Definition of Threads
- Thread: 한 개의 Process내에서 동작하는 여러 실행들.
- Pros.
1) Thread는 Process를 새로 생성하지 않기에 Process를 새로 생성하는데 드는 비용을 절약할 수 있습니다.
2) IPC(Inter Process Communication)를 사용하지 않아도 되므로, 데이터 교환이 상대적으로 쉽습니다.
- File, Heap, Static, Code를 공유하고 Stack, Register는 개별적으로 갖습니다.
3) CPU를 보다 효율적으로 활용할 수 있습니다.
- Cons.
1) 프로그래밍 난이도가 상승합니다.
2) 디버깅이 어렵습니다.
- POSIX 표준을 따르는 pthread를 주로 사용하며, 윈도우를 제외한 Unix계열 운영체제를 지원합니다.
- pthread 외에도 뛰어난 성능을 보여주는 thread들도 존재하지만,
이식성과 유지, 보수의 문제로 주로 pthread를 사용합니다.
9. 2. Thread Coding
- int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
pthread_create: thread 생성.
thread: pthread_t structure / attr: pthread_attr_t structure / start_routine: thread Function /
arg: thread Function Parameter.
- pthread_join: thread가 종료할 때까지 Main thread는 대기하고, thread 작업이 종료되면 자원을 해제.
동기화가 가능해지고, 원하는 타이밍에 반환 값을 얻을 수 있습니다.
- int pthread_join(pthread_t thread, void **value_ptr);
thread: pthread_t structure / value_ptr: return value pointer.
- int pthread_detach(pthread_t thread);
pthread_detach: 실행 중인 thread를 Main thread와 분리시키고,
thread가 작업 후 종료될 때, 자동으로 자원을 해제.
비동기적으로 종료되며, 반환 값을 얻기가 불가능합니다.
- ptrhread_create와 작업수행 후, 반드시 pthread_join, pthread_detach를 해주는 것이 좋습니다.
pthread가 종료가 안되면서 메모리 누수가 발생할 수 있기 때문입니다.
[Coding]
#include<stdio.h>
#include<pthread.h>
void *threadfunc(void *vargp);
void *threadfunc(void *vargp){
sleep(1);
printf("Hello\n");
return NULL;
}
int main(){
pthread_t tid;
pthread_create(&tid, NULL, threadfunc, NULL);
printf("main1\n");
// pthread_join(tid, NULL); // main1 -> Hello -> main2 순서로 출력.
// pthread_detach(tid); // main1 -> main2 -> Hello 순서로 출력.
printf("main2\n");
sleep(2);
return 0;
}
- 여러 개의 thread가 동시에 Shared Data에 접근하게 되면, 정상적으로 작업이 수행되지 않을 수 있습니다.
- pthread_mutex를 이용해서 Shared Data에 접근하기 전 Lock을 걸고,
사용 후 Unlock을 수행해서 작업이 정상적으로 수행되도록 할 수 있습니다.
pthread_mutex_t m_lock; // Declaration
pthread_mutex_init(&m_lock, NULL);
…
pthread_mutex_lock(&m_lock);
Shared Data Coding…
pthread_mutex_unlock(&m_lock);
…
pthread_mutex_destroy(&m_lock);
'Computer Science > Unix' 카테고리의 다른 글
11. TCP (0) | 2025.03.18 |
---|---|
10. Socket (0) | 2025.03.17 |
08. Fork and Exec (0) | 2025.03.15 |
07. Process (0) | 2025.03.14 |
06. File System (0) | 2025.03.11 |