除了submit,Exectuor還為我們提供了map方法,和內(nèi)建的map用法類似,下面我們通過兩個例子來比較一下兩者的區(qū)別。
使用submit操作回顧
# example3.pyimport concurrent.futuresimport urllib.requestURLS = ['http://httpbin.org', 'http://example.com/', 'https://api.github.com/']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 promptlywith concurrent.futures.ThreadPoolExecutor(max_workers=3) 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 = http://www.chinaznyj.com//GuoNeiZiXun/future.result()"hljs-keyword" style="color: #333333; font-weight: bold;">except Exception as exc: print('%r generated an exception: %s' % (url, exc)) else: print('%r page is %d bytes' % (url, len(data)))
從運行結(jié)果可以看出, as_completed不是按照列表的順序返回的 。
ziwenxie :: ~ » python example3.py'http://example.com/' page