Skip to content

Instantly share code, notes, and snippets.

@seozed
Created January 4, 2018 08:11
Show Gist options
  • Save seozed/840067a601d944c59f5d0faf1aa5a9f5 to your computer and use it in GitHub Desktop.
Save seozed/840067a601d944c59f5d0faf1aa5a9f5 to your computer and use it in GitHub Desktop.
一个高度抽象多线程模块示例
import concurrent.futures
import urllib.request
URLS = ['http://www.163.com/',
'http://www.qq.com/',
'http://www.baidu.com/',
'http://www.v2ex.com/',
'http://www.360.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)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment