Kim Jinung

Python - GIL(Global Interpreter Lock) 본문

Language/Python

Python - GIL(Global Interpreter Lock)

Kim Jinung 2022. 11. 23. 00:16
 

What Is the Python Global Interpreter Lock (GIL)? – Real Python

Python's Global Interpreter Lock or GIL, in simple words, is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter at any one time. In this article you'll learn how the GIL affects the performance of your Python prog

realpython.com

 

What is the Python Global Interpreter Lock (GIL)?

Understanding the purpose of Global Interpreter Lock in Python and how it impacts multi-threading

towardsdatascience.com


1. GIL이 무엇인가?

GIL은 하나의 쓰레드만 파이썬 인터프리터를 점유할 수 있도록 한다.

 

단일 쓰레드만을 사용하는 프로그램에서는 영향을 느낄 수는 없고, 멀티 쓰레드와 CPU코어를 적극 활용하는 프로그램에서는 병목현상을 초래할 수 있다. 이러한 이유로 파이썬에서 악명 높은 기능으로 명성을 얻게 되었다.

 

2. 왜 Python은 GIL을 선택했을까?

1. CPython의 메모리 관리

  • CPython의 메모리 관리는 thread safety 하지 않다.
  • 파이썬에서 멀티 쓰레드 프로그램이 실행될 때 쓰레드들은 같은 메모리를 공유한다.
  • 그러므로 각 쓰레드가 공유 데이터에 접근하는 정확한 순서를 알 수가 없어진다. (race condition 발생 가능)
  • GIL은 아예 하나의 쓰레드만 파이썬 인터프리터를 실행하는 방법으로 thread safety를 보장

2. Python의 등장 시점과 언어의 목적

  • Python은 운영체제에 멀티 쓰레드가 존재하기 이전부터 등장한 언어
  • 유저가 쉽게 배워서 빠르게 사용할 목적으로 만든 언어
  • GIL은 쓰레드에서 안전한 메모리 관리를 비교적 쉽게 구현하고 적용 가능함

3. etc.

  • C extension, CPU-bound 프로그램이 아닌 이상은 GIL에 의해서 문제가 생기는 경우는 걱정하지 않아도 된다.
  • I/O, Image processing 대부분 작업은 GIL 바깥에서 실행된다.
  • JPython, PyPy, IronPyhon 등의 인터프리터는 GIL을 포함하지 않으므로 GIL을 회피하는 방법으로 사용할 수 있다.
  • nogil 이라는 PoC가 진행 중이다.

 

'Language > Python' 카테고리의 다른 글

Python - Counter  (0) 2022.12.06
Python - for/else  (0) 2022.12.02
Python - Regular Expression  (0) 2022.11.30
Python - container, iterable, iterator, generator  (0) 2022.11.22
Python "Class method" vs "Static method" vs "Instance method"  (0) 2022.11.16