2015-10-19 91 views
1

通知多个线程我新的线程和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

什么是'http_lib'? –

+0

有一个实用工具,我有有方法来发送HTTP请求。 –

回答

1

你是什么意思的“在同一时间”,线程并行工作,但你不能在同一时间开始线程,因为python是一种脚本语言,它逐行执行。但是,一种可能的解决方案是,您可以逐个启动线程,然后在线程内,等待某个标志触发并在所有创建的线程中保持该标志全局。当该标志变为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()