07. 쓰레드의 이해

개발 99·2025년 4월 4일

공룡책

목록 보기
7/22

메모리에 여러 process가 로드된 상태에서 cpu가 concurrent하게 context switch를 해서 처리한다.

프로세스 내 Thread id가 cpu를 점유한다.
( program counter, register set, stack도 thread ID별 달라야 한다.)


여러 API 요청이 오더라도 여러 Thread가 처리를 해준다.(Non - Blocking)

장점

  • Responsiveness
    Non Blocking으로 excution을 계속 실행하면 됨.

  • Resource Sharing
    thread는 code와 data를 공유한다.( 리소스 절감 )

  • Economy
    PCB를 바꾸는 것이 Thread의 Context switch보다 싸다

  • Scalability

Java에서 thread 실행

  • Thread 클래스 상속 ( 다중 상속 안됨 )

  • Thread 인터페이스 구현

  • Lambda( 굳이 클래스를 만들 필요가 없다. )

Thread는 거진 무한 루프로 사용한다.

public class ThreadExample1{
	public static void main(String[] args){
    	MyThread1 thread = ...
        thread.start();
        System.out.println(...);
    }
}

thread가 print를 한 후, context switch가 발생한다.

부모 쓰레드의 대기(wait) join

public static void main(...){
	
    Thread thread = new Thread(
    	...
    );
    thread.start();
    
    try{
    	thread.join();
    }
    catch(Exception e){
    	...
    }

}

main 스레드는 자식 스레드가 완료를 하기 전까지 대기를 한다.

쓰레드의 종료(stop) interrupt

public void main(String args[]){
    Thread thread = new Thread(
    	...
    );
    
    thread.start();
    Thread.sleep(500);
    thread.interrupt();
}

sleep, interrupt는 block을 발생시킨다.
start는 "비동기" + "논 블로킹 방식"이다.

Multithreading in a Multicore system

여러 코어가 여러 스레드를 점유해서 context switch 비용을 줄일 수 있다.

  • single-core : threads가 interleaved된다.(작업을 사이사이 끼워넣음)

  • multiple-core : 병렬로 실행이 가능

Programming Challenges

  • Identifying tasks: 작업을 분리시킬 수 있는 지점을 찾아야 한다.

  • Balance : 각 스레드는 동일한 작업량을 수행해야 한다.

  • Data splitting

  • Data dependency


요즘은 분산시스템

동시성 vs 병렬성 = context switch

profile
구구구구구!

0개의 댓글