【发布时间】:2013-01-21 15:20:20
【问题描述】:
我正在编写一个非常基本的用 Python 编写的多线程网络爬虫,并为爬取页面和提取 url 的函数使用 While 循环,如下所示:
def crawl():
while True:
try:
p = Page(pool.get(True, 10))
except Queue.Empty:
continue
# then extract urls from a page and put new urls into the queue
(完整的源代码在另一个问题中:Multi-threaded Python Web Crawler Got Stuck)
现在理想情况下,我想在 While 循环中添加一个条件,以使 while 循环在以下情况下退出:
池(存储 url 的 Queue 对象)为空,并且;
所有线程都处于阻塞状态,等待从队列中获取 url(这意味着没有线程将新 url 放入池中,因此让它们等待没有意义,并且会使我的程序卡住。)
例如:
#thread-1.attr == 1 means the thread-1 is blocking. 0 means not blocking
while not (pool.empty() and (thread-1.attr == 1 and thread-2.attr == 1 and ...)):
#do the crawl stuff
所以我想知道是否有一个线程可以检查其他活动线程正在做什么,或者其他活动线程的状态或属性值。
已经阅读了threading.Event()的官方文档,但还是没搞明白。
希望有人能指点我的路:)
非常感谢!
马库斯
【问题讨论】:
标签: python python-2.7 python-multithreading