[파이썬] 멀티 프로세싱(Multi-processing)

이신우·2021년 7월 4일
0

용어 정리

멀티 프로세싱을 알아보기 전에 스레드와 프로세스의 차이를 보자🧐

  • 프로세스(Process)

    프로세서(Processor)에 의해 처리되는 상태

  • 쓰레드(Thread)

    프로세스(Process) 내에서 실행되는 흐름의 단위

그렇다면 멀티 스레딩과 멀티 프로세싱은 뭘까?🤔

멀티 프로세싱 vs 멀티 스레딩

  • 멀티 프로세싱(Multi-processing)

    하나 이상의 프로세스(Process)가 서로 협력하여 일을 처리하는 것

  • 멀티 스레딩(Multi-Threading)

    하나의 프로세스(Process) 내에서 둘 이상의 스레드(Thread)가 동시에 작업을 수행하는 것

각각의 장단점

  • 멀티 프로세스
    장점 : 하나의 프로세스가 죽더라도 다른 프로세스에 영향을 주지 않아 안정성이 높다.
    단점 : 멀티 스레드보다 많은 메모리공간과 CPU 시간을 차지하는 단점이 있다.

  • 멀티 스레드
    장점 : 멀티 프로세스보다 적은 메모리 공간을 차지하고 문맥 교환(Context Switching)이 빠르다.
    단점 : 자원 공유 문제와 하나의 스레드 장애로 전체 스레드가 종료 될 위험이 있다.

하지만 파이썬에서는 GIL(Global Interpreter Lock) 때문에 한번에 하나의 스레드에게만 모든 자원 점유를 허락한다...고 한다😅

파이썬 멀티 프로세싱

단일 프로세스

소요시간 : 약 3.483초

import time
from threading import Thread

def work(id, start, end, result):
    total = 0
    for i in range(start, end):
        total += i
    result.append(total)
    return


if __name__ == "__main__":
    start_time = time.time()
    START, END = 0, 100000000
    result = list()
    th1 = Thread(target=work, args=(1, START, END, result))
    
    th1.start()
    th1.join()
    
    end_time = time.time()
    print(f"Result: {sum(result)}")
    print(f"total elapsed time : {end_time - start_time}")

멀티 프로세스

소요시간 : 약 1.824초

import time
from multiprocessing import Process, Queue

def work(id, start, end, result):
    total = 0
    for i in range(start, end):
        total += i
    result.put(total)
    return

if __name__ == "__main__":
    start_time = time.time()
    START, END = 0, 100000000
    result = Queue()
    th1 = Process(target=work, args=(1, START, END//2, result))
    th2 = Process(target=work, args=(2, END//2, END, result))
    
    th1.start()
    th2.start()
    th1.join()
    th2.join()

    result.put('STOP')
    total = 0
    while True:
        tmp = result.get()
        if tmp == 'STOP':
            break
        else:
            total += tmp
    print(f"Result: {total}")
    
    end_time = time.time()
    print(f"total elapsed time : {end_time - start_time}")

0개의 댓글