while循环如何退出

while循环如何退出

本文介绍了while循环如何退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么,在线程启动时,这段代码如何退出while语句? (请不要考虑缩进)

So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()

**编辑 *

启动线程的代码:

def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    queue.join()

推荐答案

它不必退出while语句即可终止代码.此处发生的所有事情是线程已经消耗了queue.join()返回的队列中的所有内容.

It doesn't have to exit the while statement for the code to terminate. All that is happening here is that the thread has consumed everything in the queue at which point queue.join() returns.

在主代码中对queue.join()的调用返回后,主代码将立即退出,并且由于您将该线程标记为守护程序,因此整个应用程序将退出,并且后台线程将被杀死.

As soon as the call to queue.join() in the main code returns the main code will exit and because you marked the thread as a daemon the entire application will exit and your background thread will be killed.

这篇关于while循环如何退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 09:51