我是线程和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个线程,然后让它们一起执行或逐个创建线程,让创建的线程等待它们全部完成创建然后同时执行它们吗?
答案 0 :(得分:1)
你是什么意思“同时”?,线程确实在并行行为中工作,但是你不能在相同的时间启动线程,因为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()