簡體   English   中英

while循環如何退出?

[英]How does this while loop exit?

那么,該代碼如何在線程啟動時退出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()

它不必退出while語句即可終止代碼。 這里發生的所有事情是線程已經消耗了隊列中的所有內容,這時queue.join()返回。

在主代碼中對queue.join()的調用返回后,主代碼將立即退出,並且由於您將該線程標記為守護程序,因此整個應用程序將退出,並且后台線程將被殺死。

快速答案:不會,除非在任何地方引發異常,這取決於在run調用的函數/方法。

當然,您的線程可能會從另一個線程掛起/停止,從而有效地終止了while循環。

僅當執行while True循環的內容期間發生異常時,您的代碼才會中斷。....不是退出線程的更好方法,但是它可以工作。

如果要從線程中正確退出,請嘗試將while True替換為while self.continue_loop:類的東西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()

您可以將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()

另一種方法是在添加了所有其他項目之后,將“ Stop”標志放入隊列中。 然后在線程中檢查此停止標志,如果找到則中斷。

例如。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM