목표
- Thread를 이해한다
- Pthread를 이용하여 기본적인 thread programming을 할 수 있다.
목차
1. Thread
2. Pthread
3. Pthread create / exit
4. Pthread join / detach
5. Thread에서의 변수 공유
6. 상호 배제
1. Thread
Thread란?
경량 프로세스(ligthweight process: LWP)
- 일반 프로세스는 생성 시 자신만의 메모리 영역을 할당 받는다
: PCB, code, static, heap, stack 등
- Thread : PCB와 스택만 별도로 할당 받고 나머지는 부모 프로세스와 공유
- 생성과 전환(context switch)시 프로세스보다 오버헤드가 적다
대부분 운영체제가 여러 쓰레드가 하나의 프로세스가 되도록 운영
- 새로운 프로세스 생성 시 무조건 쓰레드 생성
- exec 등으로 변경 사항이 있을 때에만 새 메모리 할당
- 프로세스 == 쓰레드 그룹
multi-thread
여러개의 병행 프로세스처럼 독립적으로 동작
- 개별적으로 스케줄 가능
- 지역변수는 독립적으로 사용
- 전역변수는 공유
- 자원을 공유하므로 효과적
Thread 사용 예제
multithreaded web server
2. Pthread
POSIX thread
- IEEE POSIX 1003.1c(1995)에서 표준 thread API로 제정
Pthread Programming
- file
#include <pthread.h>
- compile
$gcc *.c - pthread
3. Pthread create / exit
Pthread create
Arguments
- pthread_t *th : 생성된 thread에 대한 식별자에 대한 구조체 포인터
- pthread_arrt_t * attr : thread의 속성을 지정하기 위해 사용, 디폴트 속성을 NULL
- void *(start_routine)(void *) : 분기 시켜서 실행할 thread함수
- void *arg : start_routine 함수에 넘겨줄 argument
Return value
- 성공하면 0을 return, 에러가 발생하면 non-zero를 return하고 errno를 설정
Thread exit
현재 실행 중인 thread를 종료
cleanup handler : pthread_cleanup_push로 cleanup handler가 정의되어 있다면 pthread_exit가 내부적으로 호출
Arguments
- void * retval : thread가 종료할 때의 return value
4. Pthread join / detach
join
- pthread_join을 호출한 thread는 thread에 대한 종료를 기다림
- thread는 자신의 종료상태를 main thread에 통보
Detach
- thread가 프로세스와 분리
- 자신이 사용했던 자원을 바로 반납
- thread가 어떻게 종료되던지 상관이 없게 되었을 때 detach시킨다.
Thead join
waitpid()와 유사, thread가 종료하기를 기다린다.
Arguments
- pthread_t thread : join할 thread identifier
- void **thread_return : thread의 return value
Return value
- 성공하면 0, 에러가 발생하면 non-zero를 리턴하고 errno를 설정
Thread detach
thread를 분리시킨다. 분리된 thread는 pthread_join()으로 기다릴 수 없다
Arguments
- pthread_t th: detach된 쓰레드는 pthread_joind을 호출하지 않아도 자동으로 모든 resource가 free 된다.
Return value
- 성공하면 0, 에러가 발생하면 non-zero를 리턴하고 errno를 설정
5. Thread에서의 변수 공유
thread는 전역변수와 static 변수를 공유
동기화가 필요.
6. 상호 배제
- pthread_mutex_init : mutex객체 초기화
- pthread_mutex_destroy mutex : 객체 제거
- pthread_mutex_lock : mutex lock 요청
- pthread_mutex_unlock : mutex lock 해제
'Computer Science > 유닉스프로그래밍' 카테고리의 다른 글
[유닉스 시스템 프로그래밍] Ch11. 소켓 프로그래밍 기초 (0) | 2020.12.09 |
---|---|
[유닉스 시스템 프로그래밍] Ch10. 시스템V의 프로세스간 통신 (0) | 2020.11.28 |
[유닉스 시스템 프로그래밍] Ch09. 파이프 (0) | 2020.11.23 |
[유닉스 시스템 프로그래밍] Ch08. 메모리 매핑 (0) | 2020.11.16 |
[유닉스 시스템 프로그래밍] Ch07. 시그널 (0) | 2020.11.04 |