这个while循环如何退出?

时间:2011-08-18 09:40:59

标签: python multithreading while-loop

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

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()

4 个答案:

答案 0 :(得分:5)

它不必退出while语句以终止代码。这里发生的一切就是线程已经消耗了队列中{@ 1}}返回的所有内容。

只要主代码中的queue.join()调用返回主代码就会退出,并且因为您将该线程标记为守护进程,整个应用程序将退出并且您的后台线程将被终止。

答案 1 :(得分:1)

快速回答:它没有,除非在任何地方引发异常,这取决于run中调用的函数/方法。

当然,有可能你的线程被另一个线程暂停/停止,这有效地终止了你的while循环。

答案 2 :(得分:1)

只有在执行while True循环的内容期间发生异常时,您的代码才会中断....这不是退出线程的更好方法,但它可以正常工作。

如果您想从线程中正确退出,请尝试使用while True

等替换while self.continue_loop:
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
        self.continue_loop = True

    def run(self):
        while self.continue_loop:
            #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
    threads = []
    for i in range(5):
        t = ThreadUrl(queue, out_queue)
        t.setDaemon(True)
        t.start()
        threads.append(t)

    for t in threads:
       t.continue_loop = False
       t.join()

    queue.join()

答案 3 :(得分:0)

您可以将block = False或timeout = 5传递给self.queue.get()方法。如果队列中没有任何项目,这将引发Queue.Empty异常。否则AFAIK,self.queue.get()将阻止整个循环,因此甚至不会进一步进行额外的中断尝试。

def run(self):
    while True:
        #grabs host from queue
        try:
            host = self.queue.get(block=False)
        except Queue.Empty, ex:
            break
        #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()

另一种方法是在添加所有其他项目后在队列中放置“停止”标志。然后在线程中检查此停止标志并在找到时中断。

例如

host = self.queue.get()
if host == 'STOP':
    #Still need to signal that the task is done, else your queue join() will wait forever
    self.queue.task_done()
    break