LoginSignup
0
2

More than 1 year has passed since last update.

python で マルチスレッド(サンプルプログラム)

Posted at

はじめに

pythonにおける、マルチスレッドの基本的なサンプルプログラム。
threadingは標準ライブラリなので、pipは必要ない

確認環境

Windows 10
python 3.9.4

コード

import threading
import logging

# デバッグログ出力設定(どのスレッドの実行かがわかるので便利)
logging.basicConfig(level=logging.DEBUG, format="%(threadName)s: %(message)s")

# 指定最大値までの指定倍数の値を出力する
def counter(multiple=1, max=1):
    for i in range(1, max + 1):
        if i % multiple == 0:
            logging.debug(i)


if __name__ == "__main__":
    # スレッドの定義(targetは仕様する関数を指定、argsは引数を順番に指定)
    trd1 = threading.Thread(target=counter, args=(1, 10))
    trd2 = threading.Thread(target=counter, args=(2, 8))
    trd3 = threading.Thread(target=counter, args=(3, 9))
    # 処理開始
    trd1.start()
    trd2.start()
    trd3.start()

    # スレッド全体が終了するまでブロック
    for trd in threading.enumerate():
        if trd is threading.currentThread():
            continue
        trd.join()

    # 単体のブロックも可能
    # trd1.join()

    # 終了時の処理
    print("complete")

おわりに

マルチスレッドは並列処理ではなく、並行処理になる。
これが大事。

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