我是线程和python的新手,我想同时用多个(10)http请求击中服务器。我有一个发送请求的实用程序。我写了如下代码:
import time
import threading
def send_req():
start = time.time()
response = http_lib.request(ip,port,headers,body,url)
end = time.time()
response_time = start - end
print "Response Time: ", response_time
def main():
thread_list = []
for thread in range(10):
t = threading.Thread(target=send_req)
t.start()
thread_list.append(t)
for i in thread_list:
i.join()
if (__name__ == "__main__"):
main()
它运行并输出响应时间。但是,由于我一个接一个地创建线程,它们的执行似乎是顺序的,而不是并发的。我可以同时创建10个线程,然后让它们一起执行,或者一个接一个地创建线程,让创建的线程处于等待状态,直到它们都完成创建,然后同时执行它们?
你说的"at the same time"是什么意思?线程确实是并行工作的,但是你不能在同一时间启动线程,因为python是一种脚本语言,它是逐行执行的。
然而,一个可能的解决方案是,您可以一个接一个地启动线程,然后在线程中等待某个标志被触发,并使该标志在所有创建的线程中保持全局。当该标志为True时,线程将同时启动它们的进程。确保在启动所有线程后触发该标志=True。例如;
def send_req():
global flag
while flag==False:
pass # stay here unless the flag gets true
start = time.time()
response = http_lib.request(ip,port,headers,body,url)
end = time.time()
response_time = start - end
print "Response Time: ", response_time
run_once=True
def main():
flag=False
thread_list = []
for thread in range(10):
t = threading.Thread(target=send_req) # creating threads one by one
#t.start()
thread_list.append(t)
for j in thread_list: # now starting threads (still one by one)
j.start()
flag=True # now start the working of each thread by releasing this flag from False to true
for i in thread_list:
i.join()