Computer Science/Operating System

4. Multithreading

  • -
728x90
반응형

Limination of Process Model
  • Process model 문제

    fork를 통해 만들어졌기 때문에 공유가 가능함에도 불구하고 공유할 수 없는 문제가 발생

    → 공유할 수 있는 자원이라면 공유하는 것이 유리

  • Multiprocessing 이슈

    이제는 cpu가 하나의 컴퓨터에 많이 존재할 수 있음. 따라서 지금까지 짠 process를 4개의 process에 분배해서 잘 돌리면 효율이 더 증가하지 않을까

결론 resource도 optimize하고, process를 찢어서 여러개의 cpu에 돌릴 수 있게끔

→ multithread라는 개념이 등장.

Thread Model

사실 process model은 사실 매우 무겁다. 리소스도 중복이 많이 되고, fine grane하게 찢을 수 없다는 문제점이 존재.

  • 공유 불가능한 process의 component가 어떤 것이 있을까?
    1. run-time stack
    1. Program context
  • 공유하는 자원은 무엇이 있을까?

    code section, data section, other operating system resources (open files and signals)

공유 불가능한 것들을 thread쪽으로 빼자.

이를 통해 서버의 효율화를 추구하고자 함.

  • 그래서 thread의 장점이 무엇인가
    1. Responsiveness : 일정 부분이 오래걸리거나 blocked 되어도 여전히 responsive할 수 있게끔 하는 역할을 함.
    1. Resource sharing
    1. Economy : 메모리를 새로 할당하고, 새로운 프로세스를 생성하는 작업은 overhead가 큼. 또한, thread는 자신이 속한 process에 많은 자원들을 공유하므로, 새로운 쓰레드를 생성하거나 context switch하는 과정에서 overhead가 적다.
    1. Scalability : multiprocess를 통해 thread들이 서로 다른 processing core에서 돌 수 있다.
Process vs Thread : Logical View
  • 그렇다면 multithreading의 문제점은 무엇인가?

    공유자원 다룰 때 조심해야 한다. 사실 코드를 공유하는 것은 문제가 없음(read-only)이므로

    global variable의 경우는 조금 조심할 필요가 있음.

    → 그래서 등장한 것이 동기화문제

커널 코드를 돌고 있어도 interrupt가 오면 interrupt를 처리해야함.

kernel의 global 데이터를 공유하는 문제가 발생함

만약에 system call handler를 돌리는 와중에 interrupt가 오고 interrupt handler가 system call handler가 건드리고 있는 global variable를 걸렸다고 생각해보자. 그러면 일관성이 꺠짐

→ 그래서 동기화 문제가 발생함.

그래서 중요한 것이 global data를 concurrent하게 잘 쓸 것인가.

→ 그래서 쓰는 것이 동기화 기술. 이제는 프로그래머 입장에서 이 부분을 신경써야함.

Process vs Thread

Process는 share nothing, thread는 공유를 함

thread간 정보 공유도 쉬워짐

여러개의 cpu에 하나의 프로세스를 나눠서 돌릴 수 있다.

각 Thread별로 PCB가 존재한다.

→ 실제로는 Scheduler는 Process를 선택하는 것이 아니라 thread를 선택한다고 생각해주면 된다.

Difference between PID and TID
What is the difference between PID and TID? The standard answer would be that PID is for processes while TID is for threads. However, I have seen that some commands use them interchangeably. For e...
https://stackoverflow.com/questions/4517301/difference-between-pid-and-tid
PID와 TID의 차이가 무엇인지

결론

TID : actually the identifier of the schedulable object in the kernel

PID : the identifier of the group of schedulable objects that share memory

Multithreading Models
  • 어떻게 user-level threads management가 가능한가?
    1. 동일한 process에 있는 thread는 동일한 address space를 가진다. 즉, address space를 library입장에서 건드릴 필요가 없다.
    1. thread는 결과적으로 hardware context만 다르다. 이는 user-level process에서 충분히 가능하다.
The user-level process (Many-to-one Model)

라이브러리 형태로 제공.

→ 이렇게 되면 kernel을 손댈 필요가 없음.

Process 하나에 thread가 여러개 있음. 원하는 것은 thread 단위로 돌리고 싶은 것.

  • Run-time system이 무엇인가

    A runtime system is an engine that translates a given programming language or languages into machine code. Often used as a vague term, runtime systems can be used to refer to the collected managed hardware resources and software needed for program execution  and operation.

→ 시스템 개발자가 제공하는 run-time system을 활용. 거기 안에는 thread table이 존재. 이 상황에서 커널은 전혀 모름.

  • 문제가 무엇인가?
    1. 만약 특정 thread가 IO call을 하면 run-time system에 속한 모든 thread가 전부 다 block됨
    1. kernel 입장에서는 각 thread를 cpu를 individual하게 사용할 수 없음.

→ many to one이라고 부르기도 함

(Many user-level threads mapped to a single kernel thread)

즉, schedule의 대상은 1개의 kernel thread

Kernel level threading

thread table을 kernel이 가지고 있음.

kernel이 process에 대한 table도 가지고 있고, thread table도 가지고 있음.

→ 이를 통해 kernel이 thread단위로 scheduling이 된다.

One-to-one Model

Linux와 window는 one-to-one model이다.

  • 장점
    1. many to one보다 concurrency가 높음 (특정 thread가 block되어도 나머지는 수행가능)
    1. parallel하게 돌릴 수 있음
  • 단점

    user thread만큼 kernel thread를 만드는데 이에 대한 overhead

Many-to-Many model

one-to-one과 many-to-one방식을 혼용

→ many-to-one에서는 유저가 원하는 대로 thread를 만들 수 있었지만 parallelism이 안되고, 반면 one-to-one에서는 concurrency는 올라갔지만, 너무 많은 thread를 생성하지 않게끔 유저가 신경써야하는 문제가 발생.

→ 이를 적당히 절충 (유저는 원하는 대로 만들고, 커널은 커널 입장에서 parallel하게 돌림)

현재 대부분의 시스템에서 processing core가 증가되는 추세이므로, kernel thread를 제한시키는 것은 그다지 중요한 문제가 아니게 됨. 따라서 현재 대부분의 OS는 one-to-one mode을 차용하고 있다.

Thread Libraries
  1. Entirely in user space with no kernel support

    해당 라이브러리에 대한 코드와 자료구조는 user space 상에 존재

  1. kernel-level library supported directly by the operating system

    해당 라이브러리에 대한 코드와 자료구조는 kernel space 상에 존재

대표적으로 3가지의 thread library가 존재

  1. POSIX Pthread
  1. Windows
  1. Java
Threads Interface

standard에 대한 정의가 필요해짐

그래서 등장한 것이 Pthreads

→ 어떤 함수를 제공할 것인가?

인터페이스를 통일하자는 것. 코드를 안바꾸고 컴파일만 다시 할 수 있게끔.

Solaris / Windows

Process에 대한 자료구조도 있고 thread에 대한 자료구조도 있음

→ 2개를 같이 운영

  • Problem

    Process와 thread를 어떻게 관리할 것인가?

    → pthread로!

Linux

process가 됐든 thread가 됐든 추가적인 자료구조를 만들지 말고 1개로 통일하자.

→ Linux uses the term task rather than process or thread.

추가적으로 Clone이라는 system call을 디자인함.

  • 철학적으로 process와 thread의 차이가 무엇인가?

    Degree of sharing

fork와 비슷하게 만들어서, 얼마만큼 공유할 것인지 명시하면 된다는 개념을 제기. 그것이 clone system call

→ 인자에다가 무엇을 공유할 것인지를 명시하게 요구!

이 때문에 사실 thread 자료구조를 따로 정의할 필요가 없음.

lightweight processes 라고 부름.

→ pcb의 이름이 task_struct라고 부른 이유 (task가 process와 thread를 아우름)

Differences between PID, TID and PPID in Linux | Baeldung on Linux
Learn the differences between Process Identifier, Thread Identifier, and Parent Process Identifier in Linux, and also how to retrieve this information using various approaches.
https://www.baeldung.com/linux/pid-tid-ppid

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.