15
26

More than 5 years have passed since last update.

pythonで平行処理入門 (threading.Thread)

Posted at

pythonでthreadingを使って平行処理する方法についてのメモです。

公式ドキュメント
https://docs.python.org/ja/3/library/threading.html

平行処理と並列処理

平行処理: 同じCPUコアの同じpythonプロセスで複数の処理を同時にやる
並列処理: 別のCPUコアの別のpythonプロセスで複数の処理を同時にやる

待機が多いような楽な処理は平行処理で、負荷が重い処理は並列処理でやるのが良いでしょう。今回は平行処理の入門記事です。

並列処理については先日書いたのでそちらを見てください
https://qiita.com/studio_haneya/items/1cf192a0185e12c7559b

試行環境

Windows10
python 3.6

平行処理の例

threading.Threadを定義してstart()で開始、join()すると終了するまで待機します。待機するのでなくis_alive()でチェックしながら別の作業をやることも出来ます。

threading.Threadは返り値を受け取れないようなので参照渡しの引数に仕込みます。ただし、受け取り用の引数を result = x * x のようにすると別の変数になってしまって返ってこないのでlistやdictで渡して書き加えて戻すようにします。

python
import time
import threading


def nijou(x, result):
    print('input: %d' % x)
    time.sleep(3)
    result[threading.current_thread().name] = x * x
    print('double:', result)


if __name__ == "__main__":
    result = dict()
    thread = threading.Thread(target=nijou, args=[4, result], name='thread1')

    thread.start()
    for k in range(6):
        time.sleep(1)
        print(thread.is_alive())
    thread.join()
    print(result)
結果
input: 4
True
True
double: {'thread1': 16}
False
False
False
False
{'thread1': 16}

ちなみに、引数も返り値も必要ない時はargsは省略可能です。
レッツトライ!

15
26
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
15
26