Python自动化(五)多线程

时间:2021-09-11 02:17:58
#coding:utf-8
import Queue
import random
import requests
import time
import threading
urls =[
'http://www.baidu.com/',
'http://www.sogou.com/',
'http://www.so.com/'
]
que = Queue.Queue()
start_time = time.time()
def get_url_content(q,url):
print "当前运行的线程是:", threading.currentThread().name
q.put(requests.get(url).content[:100])
print "线程%s运行结束:" %threading.currentThread().name
threads = []
for url in urls:
t = threading.Thread(target=get_url_content,args=(que,url))
print "当前运行的线程是:", threading.currentThread().name
t.start()
threads.append(t)

# 依次阻塞所有线程
for thread in threads:
thread.join()

while not que.empty():
print que.get()

end_time = time.time()
print "共花费时间:%s秒。" %(end_time-start_time)


再看一个简单的例子:


import threading
import time
import random
start_time =time.time()

def do_something():
print "{thread_name} start at {now}\n".format(thread_name=threading.currentThread().name,now=time.time())
time.sleep(1)
print "{thread_name} stop at {now}".format(thread_name=threading.currentThread().name,now=time.time())


if __name__== "__main__":
threads = []

# start all threading.
for i in range(1,8):
t = threading.Thread(target=do_something)
t.start()
threads.append(t)

#wait until all the threads terminnates.
for thread in threads:
thread.join()


print "all threads deid."
print "this run take {t} seconds".format(t = (time.time()-start_time))