2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python で非 async な IO 処理を並列したい場合

Last updated at Posted at 2022-03-27

概要

Python で並列処理したい場合は asyncio が便利だが、EventLoop が設定しづらかったり、IO自体が async 対応してなかったり(つまりIO終わるまで制御を握ってしまう)などの場合、純粋に並列処理したい場合がある。
その場合の方法をメモしておく。

方法

from concurrent.futures import ThreadPoolExecutor

def main():
    target_file_list = [
        'file1.dat',
        'file2.dat',
    ]
    # 平行して呼び出し
    with ThreadPoolExecutor() as executor:
        threads = [
            executor.submit(hoge.some_io_process, target_file)
            for target_file in target_file_list
        ]
        results = [
            th.result()
            for th in threads
        ]
    return results

注意点:executor.submitlambda を渡してはいけない。

下記のように lambda を渡すと target_file がループにより変わってしまい、
lambda が実行する段階では後半の(タイミング次第ではすべての)実行で
最後のファイルを参照することになってしまう。

NGの例
            executor.submit(
                lambda: hoge.some_io_process(target_file)
            )
            for target_file in target_file_list
2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?