2015-10-19 111 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()