我刚开始尝试一种同时下载多个文件的线程方式。我的实现使用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)
根据the documentation:
(着重强调)
所以当函数返回时线程应该退出。在
相关问题 更多 >
编程相关推荐