簡體   English   中英

如何讓這個線程等待隊列退出?

[英]How to get this thread waiting on a queue to quit?

我的應用程序中有兩個線程。 一個將值放入Queue ,另一個將它們從Queue中拉出並處理它們。

關閉應用程序時,我面臨兩難選擇。 處理Queue項目的線程被卡在:

item = request_queue.get() # this call blocks until an item is available

唯一能夠終止線程的是如果將另一個項添加到Queue - 並且由於主線程沒有添加任何內容(因為它正在關閉),應用程序將鎖定。

那么......即使Queue什么都沒有,我怎么能指示Queue.get()以某種方式返回?

事實證明答案很簡單。 選擇一個對處理Queue的代碼無效的值( None是理想的)並將其推入Queue 然后讓Queue處理線程在獲取值時退出:

while True:

    item = request_queue.get()

    if item is None:
        break

    # process the Queue as per normal...

由於阻塞線程不是主線程,您還可以設置.daemon = True

import time
import threading
from Queue import Queue

def getter(q):
    while True:
        print 'getting...'
        print q.get(), 'gotten'

def putter(q):
    for i in range(10):
        time.sleep(0.5)
        q.put(i)
        time.sleep(0.5)

q = Queue()
get_thread = threading.Thread(target=getter, args=(q,))
get_thread.daemon = True
get_thread.start()

putter(q)

如果在主線程中調用Queue.get(),則仍會出現此問題 - 因此setDaemon(True)答案不是通用解決方案。

例如,無法使用Ctrl-C停止此腳本

#!/usr/bin/python
import Queue

theQ = Queue.Queue()
print "one thread getting from Queue"
print theQ.get()

不是在Queue.get()上設置超時並處理異常,而是一個簡單的解決方案是進行等待循環直到有東西存在。 可以使用Ctrl-C終止此腳本

#!/usr/bin/python
import Queue
theQ = Queue.Queue()
print "one thread getting from Queue"
while theQ.empty():
    time.sleep(0.01) # or whatever value is appropriate for your event arrivals
print theQ.get()

暫無
暫無

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

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