LoginSignup
1
2

More than 3 years have passed since last update.

pythonでのマルチスレッド処理

Posted at

Pythonはマルチスレッド処理に向かない

pythonはマルチスレッドに向いていない言語と言われています。
というのも、pythonはGILを使用しているからです。

GILとは

GIL:Global Interpreter lock
バイトコードが同時に1つだけのスレッドで実行されることを保証するためのメカニズムのことです。
pythonではこれが採用されているため、基本的にはマルチスレッドはできません。

  • GILのデメリット
    同時に実行できるスレッドが1つに制限される

  • GILのメリット
    シングルスレッドのプログラムの速度向上

GILを採用しているくらいだから、並列処理はプロセスベースの方がいいのかな?と思われます。

GILを解放するモジュールもある

pythonの拡張モジュールによっては、圧縮やハッシング計算負荷の高いタスクの実行時にはGILを解放する設計になっているものもあります。

multithread.py

import threading, zipfile

# ファイルを圧縮するクラス. GILが解放される​
class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) #通常圧縮
        f.write(self.infile)
        f.close()
        print('background zip compress process finished : ', self.infile)

# mydata.txtは適当に準備
background = AsyncZip('mydata.txt', 'myarchive.zip')

# バックグラウンド処理を実行させても、メインプログラムが同時に生きていることを確認
background.start()
print('main program still working')

# バックグラウンド処理が終わるまでメインプログラムが生きていることを確認
background.join()
print('main program was waiting for a background thread')

実行結果

C:\Users\NAME\.PyCharmCE2019.2\system\workspace>python3 multithread.py
main program still working
background zip compress process finished: mydata.txt
main program was waiting for a background thread
1
2
1

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
1
2