Process & Thread

프로세스: 실행 중인 프로그램으로 자원(resources)과 쓰레드(thread)로 구성, OS에서 PID로 관리, 자신만의 메모리 공간 가짐

 

스레드: 프로세스 내에서 실제 작업을 수행 - 프로세스는 하나 이상의 쓰레드로 실행

-프로세스에서 나누어지는 일의 단위

-메모리를 다른 스레드와 공유, 한 스레드가 메모리를 잘 못 건드리면 다른 스레들에 영향을 미침

-전역 변수와 힙 메모리, 파일 디스크립터 공유

-스레드간 컨택스트 스위칭 또는 스레드간 통신이 프로세스 보다 훨씬 빠름

 

스레드는 프로세스와는 다르게 메모리 공유 가능

메모리 공유 사용으로 인하여 동기화 문제 발생

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <pthread.h>
#include <stdio.h>
 
void* thread_routine(void* arg)
{
    printf("[%s:%s] : %d\n", __FILE__, __FUNCTION__, __LINE__);
    return arg;
}
 
int main(int argc, char** argv)
{
    pthread_t thread_id;
    void *thread_result;
    int status;
    status = pthread_create(&thread_id, NULL, thread_routine, NULL);
    if (status != 0)printf("Create thread: %x \n", status);
    status = pthread_join(thread_id, &thread_result);
    if (status != 0printf("thread Join:%x\n", status);
    return (thread_result == NULL) ? 0 : 1;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none; color:white">cs

 

 

 

경량화 된 프로세스: 프로세스와 마찬가지로 동시실행 가능, 프로세스 단점 극복하기 위해 등장

프로세스와 차이점: Stack 메모리외 나머지 공간을 공유, 보다 간단한 Context switching

 

 

Single / Multi Thread

전통적으로 Single process는 single thread

Multi Thread는 한 번에 여러 작업(Task)을 수행할 수 있다.

 

Multi Thread의 장점

Responsivencess, UI에서 입력이 멈춘 경우에도 태스크를 진행할 수 있다.

Resource Sharing, 프로세스의 자원을 공유할 수 있다. Shared memory, message passing 보다 쉽다.

Economy, 프로세스 생성보다 저비용, thread switching이 context swtching 보다 낮은 점유율 (lower overhead)

Scalability, Multiprocessor 아키텍처에서 우위를 얻는다.

 

 

Multi-Threading models

Many-to-One

-사용자 수준 스레드로 하나의 커널 스레드에 관련된다.

-한 스레드가 블로킹하면 모두 갖힌다.

-멀티코어에서 병렬로 실행하지 않는다.

-Solaris green thread, GNU protable thread

 

One-to-One

-각 사용자 수준 스레드가 커널 스레드를 생성한다.

-many-to-one 보다 더욱 동시성을 갖는다.

-Windows, Linux, Solaris 9 이후

 

Many-to-Many

-다수의 사용자 수준 스레드가 다수의 커널 스레드에 관련된다.

-OS가 적절한 수의 커널 스레드를 생성한다

-Solaris 9 이전

-Windows의 ThreadFiber 패키지

 

 

Thread Libraries

라이브러리는 스레드를 생성하고 관리하는 API를 제공, 사용자 수준과 커널 수준 라이브러리가 있다

 

Pthread

-사용자 수준 혹은 커널 수준 라이브러리가 있다. gcc-v로 스레드 모델 확인 가능

-스레드와 동기화에 대한 POSIX API로 구현물이 아니고 명세서

 

Windows Thread, 커널 수준 라이브러리

 

Java Thread, 호스트 시스템에서 가능한 스레드 라이브러리를 사용

 

 

User Threads 와 Kernel Threads

User Threads

-관리가 사용자 수준에서 완료된다.

-세가지 주요 라이브러리가 있다. POSIX pthread, Windows thread, Java thread

 

Kernel Threads

-Kernel에서 지원한다

-일반적인 OS에서 모두 지원하고 있다. Windows, Solaris, Linux, Mac OS X ...

 

 

pthread 특징

일반 시스템 함수는 정수형 반환시 보통 -1 실패, 포인터형 NULL이 실패. 실패 원인은 에러코드 참조.

 

pthread 함수들은 성공시 0, 실패시 errorno에 값을 직접 반환, 포이터 반환 함수는 실패가 없는 함수

 

pthread 함수들은 Signal에 인터럽트 되지 않는다.

-EINTR 에러가 발생하지 않는다: 스레드가 인터럽트되면 데드락, 우선순위 역전 같은 복잡한 문제 때문

-다만 내부적으로 시그널 인터럽트시 재시작 설계가 많다.

 

시그널로 실패하지 않는다고 시그널 핸들러에 사용하도록 하는 것은 아니다. 금지해야 한다.

 

pthread_create() : thread 생성

pthread_join() : 특정 thread가 끝날때까지 기다림

pthread_detach() : 해당 메인 스레드로 부터 분리함

pthread_self() : 자신의 스레드 ID

pthread_mutex_init() : mutex 생성

pthread_mutex_lock() : 임계영역 시작

pthread_mutex_unlock() : 임계영역 종료

pthread_mutex_destroy : mutex 제거

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdio.h>
#include <pthread.h>
 
void *thread_summation(void *arg);
 
int sum = 0;
 
int main(int argc, char *argv[])
{
    pthread_t id_t1, id_t2;
    int range1[] = { 1,5 };
    int range2[] = { 6,10 };
 
    pthread_create(&id_t1, NULL, thread_summation, (void *)range1);
    pthread_create(&id_t2, NULL, thread_summation, (void *)range2);
 
    pthread_join(id_t1, NULL);
    pthread_join(id_t2, NULL);
 
    printf("result: %d \n", sum);
    return 0;
}
 
void *thread_summation(void *arg)
{
    int start = ((int*)arg)[0];
    int end = ((int*)arg)[1];
 
    while (start <= end)
    {
        sum += start;
        start++;
    }
    return NULL;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none; color:white">cs

 

스레드와 임계영역

임계영역, 두개 이상의 쓰레드에 의해서 공유되는 메모리 공간에 접근하는 코드 영역

스레드의 동기화, 공유된 메모리에 둘 이상의 스레드가 동시 접근 하는 것을 막는 방법. 둘 이상의 스레드 실행 순서를 컨트롤하는방법

 

대표적인 동기화 기법:

뮤텍스(프로세스 자원으로 단일 프로세스에서만 사용가능), 세마포 (커널자원으로 프로세스간 사용가능)

 

Mutex 뮤텍스

Mutual Exclusion의 줄임말, 쓰레드들의 동시접근을 허용하지 않겠다는 의미

Pthread_mutex_t 타입변수를 가르켜 흔히 뮤텍스라고 함

 

뮤텍스의 기본원리

-임계영역에 들어갈 때 뮤텍스를 잠그고 들어감

-임계영역을 빠져 나올 때 뮤텍스를 풀고 나옴

 

뮤텍스 지원 함수

pthread_mutex_init() : 초기화

pthread_mutex_lock() : 잠금

pthread_mutex_unlock() : 잠금해제

pthread_mutex_destroy() : 제거

 

 

+ Recent posts