Skip to content

Instantly share code, notes, and snippets.

@zhyq0826
Last active September 5, 2016 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhyq0826/c5a8c999093479b009e0876362e5c506 to your computer and use it in GitHub Desktop.
Save zhyq0826/c5a8c999093479b009e0876362e5c506 to your computer and use it in GitHub Desktop.
python 多线程
import urllib2
import time
from threading import Thread
def get_responses():
urls = ['http://www.baidu.com', 'http://www.amazon.cn', 'http://www.taobao.com', 'http://www.alibaba.com']
start = time.time()
for url in urls:
print url
resp = urllib2.urlopen(url)
print resp.getcode()
print "Elapsed time: %s" % (time.time()-start)
class GetUrlThread(Thread):
def __init__(self, url):
self.url = url
super(GetUrlThread, self).__init__()
def run(self):
resp = urllib2.urlopen(self.url)
print self.url, resp.getcode()
def get_responses_thread():
urls = ['http://www.baidu.com', 'http://www.amazon.cn', 'http://www.taobao.com', 'http://www.alibaba.com']
start = time.time()
threads = []
for url in urls:
t = GetUrlThread(url)
threads.append(t)
t.start()
for t in threads:
t.join()
print "Elapsed time: %s" % (time.time()-start)
if __name__ == '__main__':
get_responses()
get_responses_thread()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment