LoginSignup
1
0

More than 1 year has passed since last update.

concurrent.futures.ThreadPoolExecutor についての備忘録

Last updated at Posted at 2022-03-17

はじめに

複数の関数を同時に動かしたいとき、concurrent.futures.ThreadPoolExecutor を使うことがある。
引数についてメモ。

コード

import concurrent.futures
import time

def aaa(a):
    print("3a=",a*3)
    time.sleep(3)
    print("a,3sec")


def bbb(b):
    print("3b=",b*3)
    time.sleep(2)
    print("b,2sec")


A = 1
B = 2
executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
executor.submit(aaa,A)
executor.submit(bbb,B)

結果

image.png
aaa, bbb を同時に実行したため、このような結果になっている。

注意点

引数の使い方。引数(AおよびB)はカンマで区切る。

良い例
executor.submit(aaa,A)
executor.submit(bbb,B)

もし以下のように括弧で引数を用いた場合、(理由はよく知らないが)先にsubmit した関数の実行が完了してから次の関数が実行される。

悪い例
executor.submit(aaa(A))
executor.submit(bbb(B))

結果
image.png
aaaが完了してからbbbが実行されている(5秒以上かかっている)。

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