concurrent.futures.ThreadPoolExecutorコンカレントライブラリの詳細
6790 ワード
concurrent.futures
はこのモジュールとして2つのファイルが一緒に置かれているため、concurrentフォルダの下にはfuturesというフォルダしかないが、futuresの下には2つの主要ファイルthread.py
とprocess.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
は、***スレッドプール***を使用して呼び出しを非同期で実行するExecutor
のサブクラスです.concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=())
Executorのサブクラスで、最大max_workers
スレッドのスレッドプールを使用して呼び出しを非同期で実行します.max_workers
がNone
または指定されていない場合、デフォルトはマシンプロセッサの数です.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)))