[Python] GIL이란? 파이썬에서의 멀티쓰레드
by PyTong파이썬 GIL이란?
파이썬은 다른 언어 (C++ or Java)의 멀티쓰레드와 다른 점이 있다.
멀티 쓰레드가 멀티 쓰레드가 아니다
무슨 말이냐 하면 동시성을 만족하지 못한다.
위의 그림처럼 쓰레드를 3개로 나누어 실행하더라도 GIL를 가진 쓰레드만 실행되고, 나머지 쓰레드는 GIL release 되기를 기다린다.
동시성을 갖기 위해서는 멀티 프로세싱을 활용해야 한다.
다만 멀티 프로세스는 멀티 쓰레드에 비해 오버헤드나 데이터 교환 어려움 등의 단점이 있다.
멀티 쓰레드의 사용
사실상 CPU 코어나 쓰레드를 못굴리는데, 멀티쓰레드를 언제 사용하냐
I/O Bound를 해결할 때 사용한다.
DB, API, UI 등의 작업들은 CPU 작업 속도에 비해 현저히 느리기에 CPU 입장에서는 I/O 요소들로 인해 작업 손실을 일으킬 때가 있다.
그럴 때, 멀티 쓰레드를 도입하면 I/O 바운드를 해결할 수 있다.
이걸 활용하는게 비동기식 처리이다. (FastAPI가 빠르다고 하는 이유 중 하나)
물론 CPU 바운드는 멀티 프로세싱을 이용해야 한다.
GIL 해제
PC 시장은 싱글 코어의 성능을 올리는 것보다 코어 숫자를 늘리는 방향이 성능향상 더 크고 최근 CPU 들도 16, 24, 40 코어 까지도 있기에 파이썬이 CPU 제대로 활용하지 못하느 것을 파이썬 재단도 알고 있고, GIL을 없애기 위한 시도를 해왔다.
PEP 703 – Making the Global Interpreter Lock Optional in CPython | peps.python.org
In CPython, the global interpreter lock protects against corruption of internal interpreter states when multiple threads concurrently access or modify Python objects. For example, if multiple threads concurrently modify the same list, the GIL ensures that
peps.python.org
python 3.12에서 실험실 모드로 사용
PEP 684 – A Per-Interpreter GIL | peps.python.org
One related consideration is that a per-interpreter GIL will likely drive increased use of multiple interpreters, particularly if PEP 554 is accepted. Some maintainers of large extension modules have expressed concern about the increased burden they antici
peps.python.org
python 3.13에서 패키지 형태로 사용이 예상된다. (3.13이 기대되는 이유)
PEP 554 – Multiple Interpreters in the Stdlib | peps.python.org
In the interest of keeping this proposal minimal, the following functionality has been left out for future consideration. Note that this is not a judgement against any of said capability, but rather a deferment. That said, each is arguably valid. The Go la
peps.python.org
블로그의 정보
PyTong
PyTong