繁体   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