除了submit,Exectuor还为我们提供了map方法,和内建的map用法类似,下面我们通过两个例子来比较一下两者的区别。
使用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)))
从运行结果可以看出, as_completed不是按照列表的顺序返回的 。
ziwenxie :: ~ » python example3.py'http://example.com/' page