Python线程通信解决方案
我正在编写一个用Python编写的非常基本的多线程web爬虫程序,并使用While循环来实现对页面进行爬网和提取URL的功能,如下所示:Python线程通信解决方案,python,python-2.7,python-multithreading,Python,Python 2.7,Python Multithreading,我正在编写一个用Python编写的非常基本的多线程web爬虫程序,并使用While循环来实现对页面进行爬网和提取URL的功能,如下所示: def crawl(): while True: try: p = Page(pool.get(True, 10)) except Queue.Empty: continue # then extract urls from a page and put
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
(完整的源代码在另一个问题中:)
现在,理想情况下,我想向While循环添加一个条件,以使While循环在以下情况下退出:
#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
while 1:
try:
url = queue.get_nowait()
except Empty:
# Check that all threads are done.
if pool.free_count() == pool.size:
break
...
所以我想知道是否有一个线程可以检查其他活动线程正在做什么,或者其他活动线程的属性的状态或值
我已经阅读了关于threading.Event()的官方文档,但仍然无法理解
希望这里有人能给我指路:)
多谢各位
马库斯考虑一下这个解决方案:。正如这个问题的答案所说,我也建议你看看
Python中的多线程(直接使用线程)很讨厌,因此我会避免它,并使用某种消息传递或基于反应器的编程。您可以尝试从头开始实现您想要的,我现在想到了不同的解决方案:
- 使用)检查是否存在仍处于活动状态的线程
- 尝试实现一个线程池,让您知道哪些线程仍然处于活动状态,哪些线程返回到线程池,这也有限制爬网第三方网站的线程数量的好处(例如检查)
#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
while 1:
try:
url = queue.get_nowait()
except Empty:
# Check that all threads are done.
if pool.free_count() == pool.size:
break
...
您还可以将sentinel对象写入队列,标记爬网的完成,并存在主循环并等待线程完成(例如使用池)
您可以选择您喜欢的,希望这对您有所帮助。非常感谢您提供如此全面的答案!我决定写一本新字典来跟踪线程的状态。你的答案真的很好helpful@BananaOnTheWall:很高兴这有帮助:)