concurrent.futures.ThreadPoolExecutorコンカレントライブラリの詳細


  • concurrent.futures Python3.2が提供する新しい機能.Pythonが同時に実行する標準ライブラリです.このモジュールは、スレッドプールとプロセスプール、パラレルプログラミングタスクの管理、不確実性を処理する実行プロセス、プロセス/スレッド同期などの機能を有する.concurrent.futuresはこのモジュールとして2つのファイルが一緒に置かれているため、concurrentフォルダの下にはfuturesというフォルダしかないが、futuresの下には2つの主要ファイルthread.pyprocess.pyがある.
  • concurrent.futures.Executor:これは仮想ベースクラスであり、非同期実行の方法を提供する.
  • submit(function, argument):スケジューリング関数(呼び出し可能なオブジェクト)の実行は、argumentをパラメータとして入力する.
  • map(function, argument):argumentをパラメータとして関数を実行し、非同期で実行します.
  • shutdown(Wait=True):実行者にすべてのリソースを解放させる信号が送信される.
  • concurrent.futures.Future:関数の非同期実行を含む.Futureオブジェクトは、submitタスク(パラメータ付きfunctions)からexecutorへのインスタンスです.

  • Executorは抽象クラスで、サブクラス、すなわちスレッドまたはプロセスのExecutorPoolsにアクセスできます.スレッドまたはプロセスのインスタンスはリソースに依存するタスクであるため、再利用可能なlauncherまたはexecutorとして「プール」として整理することが望ましい.
  • ThreadPoolExecutor ThreadPoolExecutorは、***スレッドプール***を使用して呼び出しを非同期で実行するExecutorのサブクラスです.
    concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=())
    
    Executorのサブクラスで、最大max_workersスレッドのスレッドプールを使用して呼び出しを非同期で実行します.max_workersNoneまたは指定されていない場合、デフォルトはマシンプロセッサの数です.
    import concurrent.futures
    import urllib.request
    
    URLS = ['http://www.foxnews.com/',
            'http://www.cnn.com/',
            'http://europe.wsj.com/',
            'http://www.bbc.co.uk/',
            'http://some-made-up-domain.com/']
    
    # Retrieve a single page and report the URL and contents
    def load_url(url, timeout):
        with urllib.request.urlopen(url, timeout=timeout) as conn:
            return conn.read()
    
    # We can use a with statement to ensure threads are cleaned up promptly
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        # Start the load operations and mark each future with its URL
        future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
        for future in concurrent.futures.as_completed(future_to_url):
            url = future_to_url[future]
            try:
                data = future.result()
            except Exception as exc:
                print('%r generated an exception: %s' % (url, exc))
            else:
                print('%r page is %d bytes' % (url, len(data)))