2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

python 3.13t GIL無効化設定 - ①CPU-Bound並行実行

Last updated at Posted at 2024-11-11

はじめに

2024年10月、GIL無効化設定が可能のpython 3.13が正式にリリースされました。
GIL有効・無効により、CPU-Bound・IO-Bound処理の動作を検証してみました。

環境

  • python: 3.13
    python3.13をinstallした後、python.exeとpython3.13t.exeが作成されます。後者はfree-threadingのGIL無効版です。
    image.png
  • OS: windows 11
  • other: Powershell

並行実行(Concurrency)

CPU-Bound

Code(multi_threads_cpu_print.py 疑似CPU-Bound)

from threading import Thread
import sys

execution_log = []

def countdown(obj, n1):
    while n1>0:
        execution_log.append(obj)
        n1 -= 1

def cpu_bound_multi():
    t1 = Thread(target=countdown, args=("a",5000))
    t2 = Thread(target=countdown, args=("bb",500))

    t1.start()
    t2.start()

    t1.join()
    t2.join()

if __name__ == '__main__':
    cpu_bound_multi()
    with open(sys.argv[1], "w") as file:
        file.write("\n".join(execution_log))

GIL有効の場合、CPU-Bound処理の並行実行ができない

PS C:\> python.exe -c "import platform,sys; print(f'{platform.python_version()}, GIL: {sys._is_gil_enabled()}')"
3.13.0, GIL: True

PS C:\> python.exe multi_threads_cpu_print.py output_cpu_gil_true.txt
  • output_cpu_gil_true.txt
    Thread-1の処理が完了した後、Thread-2の処理が開始したことを確認しました。
    image.png

GIL無効の場合、CPU-Bound処理の並行実行ができる

PS C:\> python3.13t.exe -c "import platform,sys; print(f'{platform.python_version()}, GIL: {sys._is_gil_enabled()}')"
3.13.0, GIL: False

PS C:\> python3.13t.exe multi_threads_cpu_print.py output_cpu_gil_false.txt
  • output_cpu_gil_false.txt
    Thread-1とThread-2の処理が交替に実行されていたことを確認できました。
    image.png

IO-Bound

Code(疑似IO-Bound)

import time
from threading import Thread
execution_log = []
def sleep_(obj):
    n = 5

    while n>0:
        execution_log.append(obj)
        n -= 1
        time.sleep(0.1)

def io_bound_multi():
    t1 = Thread(target=sleep_, args=("a",))
    t2 = Thread(target=sleep_, args=("bb",))

    t1.start()
    t2.start()

    t1.join()
    t2.join()

    
if __name__ == '__main__':
    io_bound_multi()
    print(execution_log)

GIL有効・無効と関係なく、IO-Bound処理の並行実行ができる

PS C:\> python.exe multi_threads_io_print.py
['a', 'bb', 'a', 'bb', 'a', 'bb', 'a', 'bb', 'a', 'bb']

PS C:\> python3.13t.exe multi_threads_io_print.py
['a', 'bb', 'a', 'bb', 'a', 'bb', 'a', 'bb', 'a', 'bb']
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?