파이썬 멀티프로세싱 vs 멀티스레딩

Seongho·2022년 2월 13일
0

Python

목록 보기
3/3

https://monkey3199.github.io/develop/python/2018/12/04/python-pararrel.html

GIL(Global Interpreter Lock)

언어에서 자원을 보호하기 위해 락(Lock) 정책을 사용하고 그 방법 또한 다양하다. 파이썬에서는 하나의 프로세스 안에 모든 자원락(Lock)을 글로벌(Global)하게 관리함으로써 한번에 하나의 쓰레드만 자원을 컨트롤하여 동작하도록 한다.

위의 코드에서 result 라는 자원을 공유하는 두 개의 쓰레드를 동시에 실행시키지만, 결국 GIL 때문에 한번에 하나의 쓰레드만 계산을 실행하여 실행 시간이 비슷한 것이다.

GIL 덕분에 자원 관리(예를 들어 가비지 컬렉팅)를 더 쉽게 구현할 수 있었지만, 지금처럼 멀티 코어가 당연한 시대에서는 조금 아쉬운 것이 사실이다. 그렇다고 파이썬의 쓰레드가 쓸모 없는 것은 아니다. GIL이 적용되는 것은 cpu 동작에서이고 쓰레드가 cpu 동작을 마치고 I/O 작업을 실행하는 동안에는 다른 쓰레드가 cpu 동작을 동시에 실행할 수 있다. 따라서 cpu 동작이 많지 않고 I/O동작이 더 많은 프로그램에서는 멀티 쓰레드만으로 성능적으로 큰 효과를 얻을 수 있다.

https://engineering.contentsquare.com/2018/multithreading-vs-multiprocessing-in-python/

  • There can only be one thread running at any given time in a python process.
  • Multiprocessing is parallelism. Multithreading is concurrency.
  • Multiprocessing is for increasing speed. Multithreading is for hiding latency.
  • Multiprocessing is best for computations. Multithreading is best for IO.
  • If you have CPU heavy tasks, use multiprocessing with n_process = n_cores and never more. Never!
  • If you have IO heavy tasks, use multithreading with n_threads = m * n_cores with m a number bigger than 1 that you can tweak on your own. Try many values and choose the one with the best speedup because there isn’t a general rule. For instance the default value of m in ThreadPoolExecutor is set to 5 [Source] which honestly feels quite random in my opinion.

입출력 위주라면 멀티스레딩을, CPU 사용 위주라면 멀티프로세싱을 하자.

멀티프로세싱시에 CPU 코어 수를 넘겨가며 사용하지 마라.

멀티스레딩을 할 때에는 m * 코어수 만큼 스레드를 만드는데, m은 네가 알아서 조정해라. (필요한 만큼?)

=> 매칭할 때에는 멀티프로세싱

=> 데이터 가져올때는 멀티스레딩

1개의 댓글

comment-user-thumbnail
2023년 7월 6일

"멀티스레딩을 할 때에는 m * 코어수 만큼 스레드를 만드는데"에서
m이 정수인가요? 1보다 작은 소수 인가요?

답글 달기