等待并同时通知多个线程python

Wait and notify multiple threads at the same time python

我是线程处理的新手,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 时,您的线程将同时启动它们的进程。确保在启动所有线程后触发 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()