concurrent.futures.ThreadPoolExecutorを使ってみる

Python 3.2から追加されたconcurrent.futuresモジュール。
ThreadPoolExecutorを使うと、スレッドプールで処理を実行できる。

コード

main.py

import time
import threading
from concurrent.futures import ThreadPoolExecutor


def spam():
    for i in range(3):
        time.sleep(1)
        print("thread: {}, value: {}".format(threading.get_ident(), i))


def main():
    tpool = ThreadPoolExecutor(max_workers=3)
    for i in range(6):
        print("Threads: {}".format(len(tpool._threads)))  # スレッド数を表示
        tpool.submit(spam)
    print("main thread exit.")

実行結果

(venv) tokibito@tokibito-MacBookAir:~/sandbox$ python -c "import main;main.main()"
Threads: 0
Threads: 1
Threads: 2
Threads: 3
Threads: 3
Threads: 3
main thread exit.
thread: 140208052463360, value: 0
thread: 140208044070656, value: 0
thread: 140208035677952, value: 0
thread: 140208052463360, value: 1
thread: 140208044070656, value: 1
thread: 140208035677952, value: 1
thread: 140208052463360, value: 2
thread: 140208044070656, value: 2
thread: 140208035677952, value: 2
thread: 140208052463360, value: 0
thread: 140208044070656, value: 0
thread: 140208035677952, value: 0
thread: 140208044070656, value: 1
thread: 140208052463360, value: 1
thread: 140208035677952, value: 1
thread: 140208044070656, value: 2
thread: 140208052463360, value: 2
thread: 140208035677952, value: 2
  • スレッド数は必要になったときに増える
  • max_workersを超えるタスクを投げた場合は、キューに入れられて、ワーカースレッドが暇になったら次が実行される