我试图在Python中掌握多线程。 我写了这段代码:
import requests
import threading
from time import time,sleep
start_time = time()
class myThread(threading.Thread):
def __init__(self,threadID,name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
print(self.name + " Starting")
start = time()
url = 'https://stackoverflow.com'
for i in range(20):
res = requests.post(url,timeout=5)
end = time()
print("Final Thread Time: " + str(end-start) + 'For Thread {}'.format(self.threadID))
threads = []
threadID = 1
for i in range(1,5):
thread = myThread(threadID,'thread{}'.format(threadID))
thread.start()
threads.append(thread)
threadID += 1
for t in threads:
t.join()
final_time_end = time()
print("Final Time: " + str(start_time - final_time_end))
所以基本上它在每个帖子中向一个url发送了20个帖子请求。 结果是:
Final Thread Time: 6.0695300102 For Thread 3
Final Thread Time: 6.8553800583 For Thread 1
Final Thread Time: 6.9735219479 For Thread 5
Final Thread Time: 6.5822350979 For Thread 4
Final Thread Time: 11.330765152 For Thread 2
我有一个双核CPU,我不明白为什么几乎每次我运行这个脚本时,4个线程几乎在同一时间(6s)完成,但是1个线程大约需要11s(顺便说一句,有时它们都是同时完成。)
当我使用4或3个线程运行此代码时会发生这种情况。最后一个通常需要更多时间才能完成。 在最后一个需要更多时间的线程中发生了什么?