我是线程和 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个线程,然后让它们一起执行吗?还是一个一个地创建线程,让创建的线程等待,直到它们都创建完成后同时执行?
最佳答案
“同时”是什么意思?线程确实以并行行为工作,但你不能在同一时间启动线程,因为 python 是一种脚本语言,它逐行执行。
但是,一种可能的解决方案是,您可以一个接一个地启动线程,然后在线程内等待某个标志触发,并在所有创建的线程中将该标志保持为全局。当该标志变为 True 时,您的线程将同时启动其进程。确保在启动所有线程后触发该 flag=True。 IE。;
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()
关于python - python同时等待并通知多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33208612/