# Retrieve a single page and report the URL and contents defload_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)))
with ThreadPoolExecutor(max_workers=5) as executor: future_to_url = {executor.submit(load_url, url, 1): url for url in URLS} while1: for i in future_to_url.copy().keys(): if i._state == "FINISHED": print(i.get_result()) future_to_url.pop(i) iflen(future_to_url) == 0: break
defas_completed(fs, timeout=None): if timeout isnotNone: end_time = timeout + time.time()
fs = set(fs) with _AcquireFutures(fs): # 先挑选出所有已经有结果的Future finished = set( f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]) pending = fs - finished # 创建了一个waiter对象。该对象用于threading.Event。然后将自身添加到了所有的Futures上面 waiter = _create_and_install_waiters(fs, _AS_COMPLETED)