Process

1. 프로세스 생성(복사)

2. IPC 필요

3. Context Switching

 

Thread

멀티 프로세스의 장점을 유지하고, 단점을 극복하기 위해 쓰레드(Thread) 등장

1. 쓰레드의 생성 및 Context Switching 이 프로세스 보다 빠르다

2. 쓰레드간의 데이터 교환에 특별한 기법이 필요 없다.

메모리

1. "데이터 영역" - 전역 변수, "힙(Heap) 영역" - 동적 할당, "스텍(Stack) 영역" - 함수 실행

2. 실행 흐름의 분리를 목적으로 한다면, 프로세스간의 완전한 메모리 분리가 아닌, 스텍 영역의 함수(실행 흐름)만을 분리시킨다. = 별도의 실행 흐름을 위해 스텍 영역만을 독립적으로 유지한다.

 

Process & Thread

프로세스 : 운영체제 관점에서 별도의 실행 흐름

쓰레드 : 프로세스 관점에서 별도의 실행 흐름

 

하나의 프로세스 내에서, 둘 이상의 실행 흐름을 형성하기 위한 기법

 

 

 

 

thread 생성

#include <pthread.h>

int pthread_create ( pthread_t *riestrict thread, const pthread_attr_t *restrict attr,
					 void *(*start_routine)(void*), void *restrict arg);
                     
// 성공시 0, 실패시, 0 이외의 값

// thread : 생성된 쓰레드 ID
// atrr   : 쓰레드 특성 설정, NULL은 기본 쓰레드 설정
// start_routine : 쓰레드 main 주소값(함수 포인터)
// arg    : 쓰레드 main에 전달할 매개 변수의 주소값

 

#include <pthread.h>

int pthread_join(pthread_t thread, void **status);

// 성공시 0 , 실패시 O 이외의 값 반환 

// thread : 프로세스 종료 대기 시킬 쓰레드 ID
// status : 쓰레드 main 종료시 반환값의 포인터 변수 주소값

 

 

 

 

 

 

 

 

임계 영역(Critical Section)

: 둘 이상의 쓰레드가 동시에 실행시 문제가 되는 영역

-D_REENTRANT

root@my_linux: gcc -D_REENTRANT mythread.c -o mth read -lpthread

 

 

 

 

 

 

 

 

 

 

 

 

 

 

동기화(Synchronization)

Mutex

#include <pthread.h>

int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *att r);
int pthread_mutex_destroy(pthread_mutex_t *mutex);

// 성공시 0, 실패시 0 이외의 값

// mutex : 뮤텍스 생성시 참조값
// attr  : 뮤텍스 설정
#include <pthread.h>

int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);

// 성공시 0 , 실패시 O 이외의 값 반환

Semaphore

#include <semaphor.e. h>

int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_destroy(sem_t *sem);

// 성공시 0 , 실패시 O 이외의 값 반환 
// sem     : 
// pshared : 
// value   : 
#include <semaphore.h>

int sem_post(sem_t *sem);
int sem_wait(sem_t *sem);

// 성공시 0 , 실패시 O 이외의 값 반환
// sem : 

thread 종료

리눅스의 쓰레드는, 쓰레드 main 함수를 반환했다고 해서 자동으로 소멸되지 않는다.

#include <pthread.h>

int pthread_detach(pthread_t thread);

// 성공시 0 , 실패시 O 이외의 값 반환 

pthreadjoin 함수의 호출
pthread_detach 함수의 호출