2016-10-01 82 views
1

我正在寫一個腳本,應該從一個非常大的數量或網站獲取一些圖片。第一次使用多線程,認爲這是必需的,所以得到一個好的運行時。所以問題:腳本運行,但在看似隨機數量的傳遞網站後,它不再繼續。它不完全凍結壽,時間剛好從1/100秒的感覺上升。到幾分鐘左右,有時候這麼長時間,只是關閉它而已。另外它似乎並不像某些網站特別負責,有時它會得到970個,僅有200個條目。這裏的代碼的相關部分:Python多線程凍結(?)隨機

concurrent = 200 
q = Queue(concurrent * 2) 

def main(listPath, usagePath, idListPath): 
    [...] 
    for i in range(concurrent): 
     t = Thread(target=work) 
     t.daemon = True 
     t.start() 
    try: 
     for code in usedIDs: 
      q.put(code) 
     q.join() 

    except KeyboardInterrupt: 
     sys.exit(1) 


def work(): 
    while True: 
     code = q.get() 
     picture = getPicture(code) 
     if picture is None: 
      pass # todo: find other source or default 
     if not code in usage.keys(): 
      usage[code] = list() 
     usage[code].append(picture) 
     q.task_done() 

希望我得到了所有重要的代碼。提前致謝!

+0

對於這類任務,我更願意使用[multiprocessing.dummy](https://[ /docs.python.org/3/library/multiprocessing.html#module-multiprocessing.dummy)(它使用線程),因爲它更易於使用。 – janbrohl

+0

您可能正在經歷內存泄漏。當減速發生時,您是否查看過腳本的任何分析,甚至只是查看系統資源? – n8sty

+0

您似乎將圖片存儲在內存中。如果你的程序使用了太多的內存(超過你的內存容量),那麼你的操作系統可能會使用[分頁](https://en.wikipedia.org/wiki/Paging#Performance)到磁盤來提供所需的空間 - 這是非常緩慢的。 – janbrohl

回答

0

我的壞人,問題實際上是在getPicture函數中。無論如何感謝您的答案!