当任何线程完成一个tas时终止多个线程

2024-05-13 23:29:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python和线程都不熟悉。我已经编写了python代码,它充当一个web爬虫程序,并在站点中搜索特定的关键字。我的问题是,如何使用线程同时运行类的三个不同实例。当其中一个实例找到关键字时,这三个实例都必须关闭并停止爬网。这是一些代码。

class Crawler:
      def __init__(self):
            # the actual code for finding the keyword 

 def main():  
        Crawl = Crawler()

 if __name__ == "__main__":
        main()

如何使用线程让爬虫程序同时执行三种不同的爬虫?


Tags: the实例代码self程序web站点init
3条回答

在Python中似乎没有(简单的)终止线程的方法。

下面是一个并行运行多个HTTP请求的简单示例:

import threading

def crawl():
    import urllib2
    data = urllib2.urlopen("http://www.google.com/").read()

    print "Read google.com"

threads = []

for n in range(10):
    thread = threading.Thread(target=crawl)
    thread.start()

    threads.append(thread)

# to wait until all three functions are finished

print "Waiting..."

for thread in threads:
    thread.join()

print "Complete."

有了额外的开销,您可以使用更强大的multi-processaproach,它允许您终止类似线程的进程。

我已经扩展了这个例子来使用它。我希望这对你有帮助:

import multiprocessing

def crawl(result_queue):
    import urllib2
    data = urllib2.urlopen("http://news.ycombinator.com/").read()

    print "Requested..."

    if "result found (for example)":
        result_queue.put("result!")

    print "Read site."

processs = []
result_queue = multiprocessing.Queue()

for n in range(4): # start 4 processes crawling for the result
    process = multiprocessing.Process(target=crawl, args=[result_queue])
    process.start()
    processs.append(process)

print "Waiting for result..."

result = result_queue.get() # waits until any of the proccess have `.put()` a result

for process in processs: # then kill them all off
    process.terminate()

print "Got result:", result

启动线程很容易:

thread = threading.Thread(function_to_call_inside_thread)
thread.start()

创建完成后要通知的事件对象:

event = threading.Event()
event.wait() # call this in the main thread to wait for the event
event.set() # call this in a thread when you are ready to stop

一旦触发事件,您将需要向爬网程序添加stop()方法。

for crawler in crawlers:
    crawler.stop()

然后在线程上调用join

thread.join() # waits for the thread to finish

如果您进行任何此类编程,您将需要查看eventlet模块。它允许您编写“线程化”代码,而不必考虑线程化的许多缺点。

首先,如果您是python新手,我不建议您使用面向线程。习惯这种语言,然后处理多线程问题。

也就是说,如果你的目标是并行化(你说“同时运行”),你应该知道在python中(或者至少在默认实现中,CPython)多个线程不会真正并行运行,即使多个处理器内核可用。阅读GIL(全局解释器锁)了解更多信息。

最后,如果您还想继续,请检查线程模块的Python documentation。我认为Python的文档和参考文献一样好,有很多例子和解释。

相关问题 更多 >