System Architecture

moonsyu·2026년 10월 20일

Embedded

목록 보기
24/37
post-thumbnail

프로세스의 메모리 구조

Process 구성

  • text, data, bss, stack, heap으로 구성됨
  • 각각의 구성들은 segment라고 부름
segment내용
text코드
data초기값이 할당된 변수
bss초기값이 할당되지 않은 변수
stack지역 변수
heapmalloc으로 만든 변수 (동적 변수)

예제

  • 코드를 보고 각 변수가 어떤 segment에 속하는지 확인한다.
int t;
int g = 32;

int main(){
    int q = 31;
    int *p = (int*)malloc(4);
}

변수가 속한 세그먼트를 찾는 과정

변수segment이유
t.bss초기값이 없는 전역 변수
g.data초기값이 있는 전역 변수
q.stackmain 안의 지역 변수
p.stack포인터 변수도 지역 변수
malloc(4).heapmalloc으로 동적 할당한 공간

-> p 자체는 stack에 있고, p가 가리키는 malloc(4) 공간이 heap에 만들어진다.

Multi Process

  • 여러 프로세스가 동시에 수행되는 것
  • CPU가 매우 빠른 속도로 하나씩 수행하여 동시에 실행되는 것처럼 보이는 것

Multi Thread

  • 한 Process 안에서 캐릭터들이 동시에 움직일 수 있도록 하는 것
  • OS가 API(Posix)로 지원해 줘야함

Thread

개념

  • 어떤 프로그램 에서, 특히 프로세스 내에서 시행되는 흐름의 단위
  • 함수 단위로 구성됨

Thread 프로그래밍 방식

  • Thread 사용 시 약속된 기본 형태 존재
  • API Interface 제공

Thread API

API기능
#include <pthread.h>POSIX thread 헤더 (위치: /usr/include/pthread.h)
pthread_tThread 핸들러, 값은 pthread_create()가 채워 넣음
pthread_create(&t, NULL, 함수, 파라미터)Thread 생성 후 함수 실행
pthread_join(t, NULL)Thread 종료를 기다리고 자원 정리
gcc sample.c -o ./gogo -lpthreadpthread 라이브러리를 같이 링킹

pthread_create 매개변수

매개변수타입설명
thread idpthread_t*Thread 핸들러 주소
thread 속성const pthread_attr_t*우선순위 등 설정, 이식성 문제로 보통 NULL
함수void* (*)(void*)Thread로 동작시킬 함수의 주소 (함수 포인터)
파라미터void*Thread 함수에 전달할 인자 값
  • Thread 함수는 void*를 리턴하는 형태로 작성하고, 돌려줄 값이 없으면 return NULL;
  • pthread_create()와 pthread_join()은 짝꿍 → open() / close()처럼 꼭 같이 사용한다.

예제 1. 함수 호출 vs Thread

  • 함수로 호출하면 abc()의 무한 반복 때문에 bts()가 실행되지 않는다.

  • Thread로 실행하면 abc(), bts()가 동시에 실행된다.

  • 함수 호출 버전 (~/test)

#include <stdio.h>
#include <unistd.h>

void abc(){
    while(1) {
        printf("ABC\n");
        sleep(1);
    }
}
void bts() {
    while(1) {
        printf("BTS\n");
        sleep(1);
    }
}

int main(){
    abc();
    bts();
    return 0;
}
gcc sample.c -o ./gogo
./gogo
ABC
ABC
ABC
  • abc() 의 무한 반복이 끝나지 않아 bts() 는 한 번도 실행되지 않음
  • sleep(s) : s초 동안 대기 (Linux 라이브러리, man page 3)
  • Thread 버전 (~/test2)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void *abc(){
    while(1) {
        printf("ABC\n");
        sleep(1);
    }
    return NULL;
}

void *bts(){
    while(1) {
        printf("BTS\n");
        sleep(1);
    }
    return NULL;
}

int main()
{
    pthread_t t1, t2;

    pthread_create(&t1, NULL, abc, NULL);
    pthread_create(&t2, NULL, bts, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    return 0;
}
# 빌드 (소문자 L)
gcc sample.c -o ./gogo -lpthread

# 실행
./gogo

함수 호출과 Thread 실행 비교

-> 결과: ABC, BTS가 번갈아 출력된다. 출력 순서는 실행할 때마다 다를 수 있다.

예제 2. Thread는 몇 개일까?

  • t1, t2 그리고 main() → 총 3개의 Thread가 동작 중이다.
  • main Thread는 abc, bts가 종료될 때까지 pthread_join에서 멈춰 있다.

main이 pthread_join에서 t1, t2를 기다리는 과정

-> Thread를 먼저 생성했다고 먼저 실행되는 것이 아니다. 무엇이 먼저 동작할지는 스케줄러가 정한다.

Thread & 매개변수

  • pthread_create()의 4번째 인자로 Thread 함수에 값을 전달할 수 있다.
  • 인자는 void* 타입이므로 형변환해서 사용한다.

예제 1. 변수 하나 전달

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void* abc(void* p){
    int a = *(int*)p;
    while(1){
        printf("%d\n", a);
        a++;
        usleep(300*1000);
        if( a>10 ) break;
    }
    return NULL;
}

int main(){
    pthread_t tid;
    int gv = 1;

    pthread_create(&tid, NULL, abc, &gv);
    pthread_join(tid, NULL);
    printf("thread end\n");
    return 0;
}

Thread에 int 변수를 전달하는 과정

-> 결과: 1 ~ 10이 0.3초 간격으로 출력된 뒤 thread end가 출력된다.

예제 2. 구조체 전달

#include <stdio.h>
#include <pthread.h>

struct Node{
    int y;
    int x;
};

void *abc(void *p){
    struct Node *val = (struct Node *)p;
    printf("%d %d\n", val->x, val->y);
    return NULL;
}

int main(){
    pthread_t tid;
    struct Node val = {2, 4};   // y = 2, x = 4

    pthread_create(&tid, NULL, abc, &val);
    pthread_join(tid, NULL);
    return 0;
}

Thread에 구조체를 전달하는 과정

-> 결과: 4 2

-> 자료의 실행 화면은 구조체 두 개(val1, val2)를 각각 Thread에 전달해 val1 4 2, val2 4 2 가 출력되는 형태 (소스는 일부만 수록)

-> void*는 만능이다. 변수, 구조체 상관없이 모두 받고, 역참조하는 방법도 같다.

예제 3. 반복문에서 &i를 전달하면?

  • 의도는 0 ~ 3을 출력하는 것이다.
#include <stdio.h>
#include <pthread.h>

void *run(void *arg){
    int a = *(int*)arg;
    printf("%d", a);
    return NULL;
}

int main(){
    pthread_t t[4];
    for (int i = 0; i<4; i++) pthread_create(&t[i], NULL, run, &i);
    for (int i = 0; i<4; i++) pthread_join(t[i], NULL);
    return 0;
}

4개의 Thread가 같은 i 주소를 읽어서 생기는 문제

-> 결과: 2442, 3424처럼 실행할 때마다 다르고, 같은 값이 중복되거나 4가 출력된다.

-> Thread가 언제 동작할지는 스케줄러가 정한다. Thread는 동작할 때 i의 주소를 보고 값을 가져가는데, 그때 이미 i가 바뀌어 있을 수 있다.

예제 4. 배열로 해결

  • i 값을 배열에 미리 담아두고, Thread마다 각자의 주소를 넘긴다.
#include <stdio.h>
#include <pthread.h>

void *run(void *arg){
    int a = *(int*)arg;
    printf("%d", a);
    return NULL;
}

int main(){
    pthread_t tid[4];
    int id[4];
    for (int i = 0; i<4; i++) {
        id[i] = i;
        pthread_create(&tid[i], NULL, run, &id[i]);
    }
    for (int i = 0; i<4; i++) pthread_join(tid[i], NULL);
    return 0;
}

배열로 Thread마다 다른 주소를 넘겨 해결하는 과정

-> 결과: 0321, 0213처럼 0 ~ 3이 한 번씩 출력된다. 순서는 스케줄러가 정하므로 실행할 때마다 다르다.

Thread의 메모리 공유

  • 여러 Thread가 동작 중일 때 Thread끼리 메모리를 공유
  • .text, .bss, .data, .heap → 공유, .stack → Thread마다 독립

예제 1. 메모리 영역별 주소 확인

  • 두 Thread가 같은 함수를 차례로 실행하며 변수의 주소를 출력
  • 자료에는 abc() 함수만 수록 → main() 은 Thread를 두 번 생성하도록 작성
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int a = 100;    // .data
int b;          // .bss
int *p;         // .heap 가리키는 포인터 변수

void* abc() {
    int c = 10; // .stack

    printf("=================\n");
    printf(".data  : %p\n", (void*)&a);
    printf(".bss   : %p\n", (void*)&b);
    printf(".stack : %p\n", (void*)&c);
    printf(".heap  : %p\n", (void*)p );

    return 0;
}

int main(){
    p = (int*)malloc(4);

    pthread_t t1, t2;
    pthread_create(&t1, NULL, abc, NULL);
    pthread_join(t1, NULL);
    pthread_create(&t2, NULL, abc, NULL);
    pthread_join(t2, NULL);

    free(p);
    return 0;
}
=================
.data  : 0x62f991022010
.bss   : 0x62f991022020
.stack : 0x770d97dfee44
.heap  : 0x62f994e422a0
=================
.data  : 0x62f991022010
.bss   : 0x62f991022020
.stack : 0x770d975fde44
.heap  : 0x62f994e422a0
  • .data, .bss, .heap 주소는 두 Thread에서 동일 → 공유
  • .stack 주소는 Thread마다 다름 (위 출력은 자료의 실행 결과, 실행 환경마다 값은 다름)

예제 2. 메모리 공유 문제 (Race Condition)

  • 4개의 Thread가 전역 변수 cnt 를 각각 10000번 ++ → 기대값은 40000
#include <stdio.h>
#include <pthread.h>

int cnt=0; //.data 공유되는 메모리
void* run(void* arg){
    for(int i=0; i<10000; i++) cnt++;
}

int main(){
    pthread_t tid[4];
    for(int i=0; i<4; i++) pthread_create(&tid[i], NULL, run, NULL);
    for(int i=0; i<4; i++) pthread_join(tid[i], NULL);

    printf("%d\n", cnt);
    return 0;
}
gcc sample.c -o ./gogo -lpthread
./gogo
./gogo
./gogo
18244
18606
31539
  • 실행할 때마다 결과가 달라지고 40000이 나오지 않음 (자료의 실행 결과 기준)
  • cnt++ 는 읽기 → 증가 → 쓰기 세 단계 → 여러 Thread가 같은 값을 읽어 각자 증가시키면 증가분이 사라짐
  • Race Condition: Thread/Process의 타이밍에 따라 결과가 달라질 수 있는 상태

mutex

  • 키를 기반으로 하는 상호 배제 기법
  • Critical Section에 진입할 때 잠그고, 코드를 모두 수행한 뒤 풀기
  • 키를 잃어버리면(unlock 누락) 다른 Thread가 계속 대기 → 대참사
API설명
pthread_mutex_tmutex 핸들러 객체
pthread_mutex_init(핸들러, 속성)mutex 초기화. 속성이 NULL 이면 default
pthread_mutex_lock(핸들러)mutex를 잠금. 이미 잠겨 있으면 풀릴 때까지 대기
pthread_mutex_unlock(핸들러)잠근 mutex를 풀기
pthread_mutex_destroy(핸들러)mutex 제거. 잠긴 상태에서 제거하면 EBUSY 오류

예제 3. mutex로 Critical Section 보호

#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mlock;
int cnt=0;
void *run(){
    pthread_mutex_lock(&mlock);
    for(int i=0; i<10000; i++) cnt++;
    pthread_mutex_unlock(&mlock);
}

int main(){
    pthread_mutex_init(&mlock, NULL);

    pthread_t tid[4];
    for(int i=0; i<4; i++) pthread_create(&tid[i], NULL, run, NULL);
    for(int i=0; i<4; i++) pthread_join(tid[i], NULL);

    printf("%d\n", cnt);

    pthread_mutex_destroy(&mlock);

    return 0;
}
40000
40000
  • Critical Section인 for 문을 lock / unlock 으로 감싸 한 번에 한 Thread만 실행
  • 실행할 때마다 항상 40000 출력

Thread의 종료

  • Thread를 생성한 뒤 종료를 잘 해야 사용한 메모리가 정리됨 (정리는 주로 OS의 역할)
  • pthread_cancel(pthread_t) : 특정 Thread를 종료하기 위한 목적으로 사용, pthread_cancel() 을 받은 Thread는 pthread_exit() 실행, 반환값은 성공 여부

예제 4. Thread 2에서 Thread 1 원격 종료

  • 자료에는 killABC() 와 main() 앞부분만 수록 → abc() 와 pthread_join() 은 작성
  • pthread_cancel() 로 종료할 Thread의 정보(t1)를 Thread 2 생성 시 arg 로 전달
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void *abc(void *arg) {
    while (1) {
        printf("[T1] BTS\n");
        sleep(1);
    }
    return NULL;
}

void *killABC(void *arg) {
    int count = 0;
    while (count < 10) {
        count++;
        printf("[T2] %d\n", count);
        sleep(1);
    }
    // 스레드1을 종료
    printf("Thread1 Kill\n");
    pthread_cancel(*(pthread_t *)arg);
    return NULL;
}

int main() {
    setbuf(stdout, NULL);
    pthread_t t1, t2;

    pthread_create(&t1, NULL, abc, NULL);
    pthread_create(&t2, NULL, killABC, (void *)&t1);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    return 0;
}
[T1] BTS
[T2] 1
[T1] BTS
[T2] 2
 ...
[T2] 10
Thread1 Kill
  • [T2] 가 10까지 세고 나면 Thread 1을 종료 → [T1] BTS 출력이 멈추고 프로그램 종료
  • setbuf(stdout, NULL) : 표준 출력 버퍼링을 꺼서 출력 순서를 바로 확인
  • 자료의 실행 화면에서는 Thread1 Kill 뒤에 [T1] BTS 가 한 번 더 출력됨

0개의 댓글