학교/multicore
[lec5] Pthread Programming
pasongsongeggtak
2022. 5. 23. 11:28
- Thread란?
- OS에 의해 동시적으로 실행되는 instructions의 독립적인 흐름
- MultiThread Program
- 메인 프로그램이 여러 개의 쓰레드를 가지는 경우
- Process와 Thread
- Thread는 프로세스의 리소스를 공유한다.
- 한 스레드의 변화는 다른 스레드에 영향을 미침. 같은 값을 가리키는 두 개의 포인터가 존재할 수 있음. 같은 메모리 위치에 읽고 쓰는 것은 가능하지만 synchronization이 요구됨
- 프로세스는 리소스를 공유하지 않음!
- Thread는 프로세스의 리소스를 공유한다.
- Thread의 특징
- 프로세스 내에 존재하며, 프로세스의 리소스를 공유함
- 독립적인 제어 흐름을 가짐
- 독립적으로 스케줄화될 수 있어야하는 리소스만 복제 가능
- 다른 스레드와 프로세스 리소스를 공유함
- 프로세스가 죽으면 죽음
- 프로세스 생성을 통해 overhead가 대부분 발생되었기 때문에 가벼움
- 한 프로세스 내의 쓰레드는 같은 주소 공간을 공유함
- inter-thread comm. > inter-process comm.
- pthread
- POSIX thread
- UNIX를 위한 C언어의 표준 thread
- for Portability
- 공유된 메모리를 갖는 멀티 프로세서에서 작동
- 성능 향상, 프로세스 보다 더 적은 시스템 리소스 요구
- Pthreads API
- Thread Management: thread 생성 및 파괴
- Mutexes (mutual exclusion): 동기화
- Condition Variables: mutex를 공유하는 쓰레드들 사이의 커뮤니케이션
- Thread Management
- pthread_create(thread, attr, start_routine, arg)
- 새 thread를 만들고 실행가능하게 함
- attr: default attributes로 NULL 사용
- start_routine: 쓰레드가 실행할 함수
- arg: 함수의 매개변수로 포인터로 전달, 하나만 전달 가능
- error code 체크
- pthread_exit(status) /pthread_cancel(thread)
- thread가 종료되는 경우
- thread가 실행하는 함수가 리턴되었을 때
- pthread_exit
- pthread_cancel
- exex(), exit()에 의해 전체 프로세스가 종료될 때
- main()이 먼저 종료될 때 (단 main()이 pthread_exit으로 종료되는 경우에는 다른 thread들은 살아있음)
- pthread_exit
- status: 종료 상태 지정
- pthread_exit으로 file을 닫을 수 없음
- thread가 종료되는 경우
- ex
- pthread_create(thread, attr, start_routine, arg)
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void* PrintHello(void* threadid){
int* tid;
tid = (int*)threadid;
printf("Hello World! It's me thread #%d\n", *tid);
pthread_exit(NULL);
}
int main(int args, char *argv[]){
pthread_t threads[NUM_THREADS];
int rc, t;
for (t=0; t<NUM_THREADS; t++){
printf("in main: creating thread #%d\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void*) &t);
if (rc){
printf("ERROR code is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
- JOINING
- int pthread_join(pthread_t thread, void **value_ptr);
- pthread_join() subroutine은 특정 thread가 종료될 때까지 calling thread를 막는다.
- 타겟 스레드에 pthread_exit이 있다면 타겟 스레드의 종료 상태를 알 수 있음
- joining thread는 하나의 pthread_join() 호출에 매치됨. 같은 스레드에 여러 개의 join을 시도하는 것은 error를 일으킴
- int pthread_join(pthread_t thread, void **value_ptr);
- Mutexes
- Mutual Exclusion: 동시에 critical section에 접근하는 것을 막기 위해 사용되는 알고리즘
- thread synchronization
- 공유 자원에 여러 writes가 동시에 일어나는 것을 보호
- "lock": 한 스레드만 주어진 시간 내에 mutex variable를 가질 수 있음. 다른 쓰레드들은 block 됨
- race condition을 막는데 사용됨
- race condition: 둘 이상의 쓰레드가 공유 자원을 동시에 읽거나 쓸 때, 공유 자원에 대한 접근 순서에 따라 실행 결과가 달라지는 상황
- pthread_mutex_init(mutex,attr)
- pthread_mutex_destroy(mutex)
- mutex variable: pthread_mutex_t
- 사용 전에 초기화 되어야함
- pthread_mutex_lock(mutex)
- pthread_mutex_trylock(mutex): mutex lock 시도. mutex가 이미 lock되어 있는 상태라면 busy error code 리턴
- pthread_mutex_unlock(mutex)
- Condition Variables
- thread synchronization
- 특정 조건을 만족하기를 기다리는 변수. thread간의 신호 전달을 위해 사용
- mutex lock과 함께 사용
- pthread_cond_init(condition, attr)
- pthread_cond_destroy(condition)
- pthread_cond_wait(condition, mutex)
- 조건을 만족할 때 까지 calling thread를 차단
- 뮤텍스가 lock되어 있을 때 호출 가능
- 기다리는 동안 mutex lock은 자동으로 풀림
- signal을 받고 thread가 깨어나면, mutex는 자동적으로 lock됨
- pthread_cond_signal(condition)
- condition variable에서 wait하고 있는 다른 thread에게 signal을 보내서 깨움
- pthread_cond_wait() 전에 pthread_cond_signal()이 호출되면 error
- pthread_cond_broadcast(condition)
- 하나 이상의 thread가 blocking wait state에 있으면 pthread_cond_signal()대신 broadcast 사용