我目前正在使用 Threading/workpool 测试一些东西;我创建了 400 个线程,它们总共下载了 5000 个 URL... 问题是 400 个线程中的一些线程正在“冻结”,当查看我的进程时,我看到每次运行都会冻结 +- 15 个线程,并且最终在一段时间后1比1关闭。
我的问题是是否有一种方法可以让某种“计时器”/“计数器”在 x 秒后没有完成时杀死一个线程。
# download2.py - Download many URLs using multiple threads.
import os
import urllib2
import workerpool
import datetime
from threading import Timer
class DownloadJob(workerpool.Job):
"Job for downloading a given URL."
def __init__(self, url):
self.url = url # The url we'll need to download when the job runs
def run(self):
try:
url = urllib2.urlopen(self.url).read()
except:
pass
# Initialize a pool, 400 threads in this case
pool = workerpool.WorkerPool(size=400)
# Loop over urls.txt and create a job to download the URL on each line
print datetime.datetime.now()
for url in open("urls.txt"):
job = DownloadJob(url.strip())
pool.put(job)
# Send shutdown jobs to all threads, and wait until all the jobs have been completed
pool.shutdown()
pool.wait()
print datetime.datetime.now()