Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python线程通信解决方案_Python_Python 2.7_Python Multithreading - Fatal编程技术网

Python线程通信解决方案

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

我正在编写一个用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 new urls into the queue
(完整的源代码在另一个问题中:)

现在,理想情况下,我想向While循环添加一个条件,以使While循环在以下情况下退出:

  • 池(存储URL的队列对象)为空,并且

  • 所有线程都在阻塞,等待从队列中获取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
    
    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中的多线程(直接使用线程)很讨厌,因此我会避免它,并使用某种消息传递或基于反应器的编程。

    您可以尝试从头开始实现您想要的,我现在想到了不同的解决方案:

    • 使用)检查是否存在仍处于活动状态的线程
    • 尝试实现一个线程池,让您知道哪些线程仍然处于活动状态,哪些线程返回到线程池,这也有限制爬网第三方网站的线程数量的好处(例如检查)
    如果您不想重新发明轮子,您可以使用实现线程池的现有库,或者您也可以选中使用绿色线程并提供线程池的gevent,我已经通过以下方式实现了类似的功能:

    #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:很高兴这有帮助:)