2015-06-19 59 views
0

我正在尋找實現線程模塊(python3),並且想要先測試它以瞭解它如何幫助減少運行時。下面的代碼沒有實現多線程:測試線程模塊時出錯

import threading, time 
import queue 
q = queue.Queue(10000000) 

def fill_list(): 
    global q 
    while True: 
     q.put(1) 
     if q.qsize() == 10000000: 
      return 

t1 = time.clock() 
fill_list() 
tend = time.clock() - t1 

print(tend) 

這將產生:

>>> 
29.939367999999998 
>>> 

然後我試圖完成2個線程相同的任務,努力降低運行時間。

import threading, time 
import queue 

q = queue.Queue(10000000) 

def fill_list(): 
    global q 
    while True: 
     q.put(1) 
     if q.qsize() == 10000000: 
      return 

t1 = time.clock() 
thread1 = threading.Thread(target=fill_list, args=()) 
thread2 = threading.Thread(target=fill_list, args=()) 
thread1.start() 
thread2.start() 
tend = time.clock() - t1 
print(q.qsize()) 
print(tend) 

這將產生:

>>> 
13722 
0.018415999999999988 
>>> 

所以完成得更快,但它實際上並沒有完成,我不明白的隊列填充到10000000的任務,爲什麼方法將返回如果有條件的沒有得到滿足。

我是否錯誤地實現了線程模塊?這是兩個線程試圖訪問同一隊列的問題嗎? 謝謝

回答

1

您需要等待線程完成,因爲您的主要繼續執行,而2個線程仍在運行。

加入此問題進行修復。

thread1.start() 
thread2.start() 
thread1.join() 
thread2.join() 
tend = time.clock() - t1 
+0

嗯現在它似乎是掛。當我將它從隊列更改爲列表時,儘管它有效。 – Malonge