Python如何以结束线程的方式结束函数(即减少线程.activeCount()乘以1)?

2024-09-25 00:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始尝试一种同时下载多个文件的线程方式。我的实现使用thread.start_new_线程(). 在

我想一次下载10个文件,然后等待所有10个文件完成下载,然后再开始下10个文件。在我下面的代码中,线程.activeCount()永远不会减少,即使download()以exit()结束,系统出口()或返回。在

我的解决方法是引入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)

Tags: 文件importnewoutputdownloadexiturllib线程
1条回答
网友
1楼 · 发布于 2024-09-25 00:35:49

根据the documentation

Start a new thread and return its identifier. The thread executes the function function with the argument list args (which must be a tuple). The optional kwargs argument specifies a dictionary of keyword arguments. When the function returns, the thread silently exits. When the function terminates with an unhandled exception, a stack trace is printed and then the thread exits (but other threads continue to run).

(着重强调)

所以当函数返回时线程应该退出。在

相关问题 更多 >