簡體   English   中英

Python-如何以結束線程的方式結束函數(即將threading.activeCount()減少1)?

[英]Python - How to end function in a way that ends thread (i.e. decrease threading.activeCount() by 1)?

我剛剛開始嘗試使用線程作為一次下載多個文件的方法。 我的實現使用thread.start_new_thread()。

我想一次下載10個文件,然后等待所有10個文件完成下載,然后再開始下一個10個文件。 在下面的代碼中,即使download()以exit(),sys.exit()或return結尾,threading.activeCount()也永遠不會減少。

我的解決方法是引入downloadsRemaining計數器,但是現在活動線程的數量不斷增加。 在下面的示例程序的結尾,將有500個活動線程,我實際上一次只希望有10個。

import urllib
import thread
import threading
import sys

def download(source, destination):

    global threadlock, downloadsRemaining

    audioSource = urllib.urlopen(source)
    output = open(destination, "wb")
    output.write(audioSource.read())
    audioSource.close()
    output.close()

    threadlock.acquire()
    downloadsRemaining = downloadsRemaining - 1
    threadlock.release()

    #exit()
    #sys.exit()    None of these 3 commands decreases threading.activeCount()
    #return


for i in range(50):
    downloadsRemaining = 10
    threadlock = thread.allocate_lock()

    for j in range(10):
        thread.start_new_thread(download, (sourceList[i][j], destinationList[i][j]))

    #while threading.activeCount() > 0:  <<<I really want to use this line rather than the next
    while downloadsRemaining > 0:
        print "NUMBER ACTIVE THREADS:  " + str(threading.activeCount())
        time.sleep(1)

根據文檔

啟動一個新線程並返回其標識符。 線程使用參數列表args(必須是元組)執行函數功能。 可選的kwargs參數指定關鍵字參數的字典。 當函數返回時,線程以靜默方式退出。 當函數以未處理的異常終止時,將打印堆棧跟蹤,然后線程退出(但其他線程繼續運行)。

(已添加重點。)

因此,線程應在函數返回時退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM