Threads Jo, Heeseung
Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2
Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU 자원을효율적으로사용 - 멀티프로세스방식에비해서빠른 thread 생성 데이터교환이쉬움 - IPC 를사용하지않고, 데이터를교환할수있음 기술의성숙 다른기술과융합하기가수월함 프로그래밍난이도상승 - 비직관적 - 문맥의흐름을예상하기어려움 디버깅이어려움 제대로만들기가어려움 - 병렬프로그래밍, 공유자원관리는높은기술숙련도를요구 3
POSIX Thread : pthread POSIX 표준을따르는 pthread Multi thread 프로그래밍을위한 API 를제공 뛰어난호환성 윈도우를제외한모든 Unix 계열운영체제를지원 CPU 각벤더에서도독자적인 thread API 를제공 pthread에비해서뛰어난성능을보여주지만, 이식성과유지 / 보수상의문제로대부분 pthread를이용 4
Posix Threads (pthreads) Interface pthreads: Standard interface for ~60 functions that manipulate threads from C programs Creating and reaping threads - pthread_create() - pthread_join() Determining your thread ID - pthread_self() Terminating threads - pthread_cancel() - pthread_exit() - exit() [terminates all threads], RET [terminates current thread] Synchronizing access to shared variables - pthread_mutex_init - pthread_mutex_[un]lock - pthread_cond_init - pthread_cond_[timed]wait - pthread_cond_signal 5
Thread Create int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); thread : pthread_t structure attr : pthread_attr_t start_routine : 스레드함수 arg : 스레드함수로넘길매개변수 6
Thread Create int pthread_join(pthread_t thread, void **value_ptr); thread : pthread_t structure value_ptr : return value pointer 스레드종료후 join 함수를호출해야만자원을회수할수있음 int pthread_detach(pthread_t thread); 해당메인스레드로부터분리함 스레드종료와동시에자원회수 7
The Pthreads "hello, world" Program #include <stdio.h> void *thread(void *vargp); /* thread routine */ void *thread(void *vargp) sleep(1); printf("hello, world!\n"); return NULL; int main() pthread_t tid; # gcc ex.c -lpthread #./a.out main Hello, world! main2 pthread_create(&tid, NULL, thread, NULL); printf("main\n"); pthread_join(tid, NULL); printf("main2\n"); sleep(2); return 0; 8
The Pthreads "hello, world" Program #include <stdio.h> void *thread(void *vargp); /* thread routine */ void *thread(void *vargp) sleep(1); printf("hello, world!\n"); return NULL; int main() pthread_t tid; # gcc ex.c -lpthread #./a.out main main2 Hello, world! pthread_create(&tid, NULL, thread, NULL); printf("main\n"); pthread_detach(tid); printf("main2\n"); sleep(2); return 0; 9
Thread Mutex pthread_mutex_t mutex; int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); int pthread_mutex_destroy(pthread_mutex_t *mutex); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); 10
공유 data 를사용하는 threads #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define MAX_THREAD 20 void *t_func(void *data) int *count = (int *)data; int i; pthread_t thread_id = pthread_self(); for (i=0; i<100; i++) *count = *count+1; 11
공유 data 를사용하는 threads int main(int argc, char **argv) pthread_t thread_id[max_thread]; int i = 0; int count = 0; for(i = 0; i < MAX_THREAD; i++) Main Thread : 1957 pthread_create(&thread_id[i], NULL, t_func, (void *)&count); for(i = 0; i < MAX_THREAD; i++) pthread_join(thread_id[i], NULL); # gcc ex.c -lpthread #./a.out Main Thread : 2000 #./a.out printf("main Thread : %d\n", count); return 0; 12
pthread_mutex_lock/unlock #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define MAX_THREAD 20 pthread_mutex_t m_lock; void *t_func(void *data) int *count = (int *)data; int i; pthread_t thread_id = pthread_self(); pthread_mutex_lock(&m_lock); for (i=0; i<100; i++) *count = *count+1; pthread_mutex_unlock(&m_lock); 13
pthread_mutex_lock/unlock int main(int argc, char **argv) pthread_t thread_id[max_thread]; int i = 0; int count = 0; if(pthread_mutex_init(&m_lock, NULL)!= 0) perror("mutex Init failure"); return 1; # gcc ex.c -lpthread #./a.out Main Thread : 2000 for(i = 0; i < MAX_THREAD; i++) pthread_create(&thread_id[i], NULL, t_func, (void *)&count); for(i = 0; i < MAX_THREAD; i++) pthread_join(thread_id[i], NULL); printf("main Thread : %d\n", count); return 0; 14
pthread 동기화 pthread_cond_t cond; int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr); int pthread_cond_destroy(pthread_cond_t *cond); pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex); int pthread_cond_signal(pthread_cond_t *cond); 15
pthread_cond_wait/signal #include <stdio.h> #include <unistd.h> #include <stdlib.h> pthread_mutex_t mut; pthread_cond_t cond; void *f(void *data) printf("before wait\n"); pthread_mutex_lock( &mut ); pthread_cond_wait( &cond, &mut ); printf("after wait\n"); pthread_mutex_unlock( &mut ); return 0; 16
pthread_cond_wait/signal int main(int argc, char *argv[]) int res = 0; res = pthread_mutex_init(&mut, NULL); res = pthread_cond_init(&cond, NULL); pthread_t pt; pthread_create(&pt, NULL, f, NULL); sleep(2); pthread_cond_signal(&cond); # gcc ex.c -lpthread #./a.out before wait after wait pthread_join(pt, NULL); pthread_mutex_destroy(&mut); pthread_cond_destroy(&cond); return 0; 17
pthread_* functions 수많은 pthread 지원을위한함수들이존재 Manual page 참고 man pthreads 18