简体   繁体   English

如何让这个线程等待队列退出?

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

I've got two threads in my application. 我的应用程序中有两个线程。 One that puts values in a Queue , and another that pulls them from the Queue and processes them. 一个将值放入Queue ,另一个将它们从Queue中拉出并处理它们。

I am faced with a dilemma when shutting the application down. 关闭应用程序时,我面临两难选择。 The thread that processes items in the Queue is stuck on: 处理Queue项目的线程被卡在:

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

The only thing that will terminate the thread is if another item is added to the Queue - and since the main thread doesn't add anything (because it's shutting down), the application locks. 唯一能够终止线程的是如果将另一个项添加到Queue - 并且由于主线程没有添加任何内容(因为它正在关闭),应用程序将锁定。

So... how can I instruct Queue.get() to somehow return even if there is nothing on the Queue ? 那么......即使Queue什么都没有,我怎么能指示Queue.get()以某种方式返回?

The answer it turns out is quite simple. 事实证明答案很简单。 Pick a value that would be invalid for the code that processes the Queue ( None is ideal for that) and push that into the Queue . 选择一个对处理Queue的代码无效的值( None是理想的)并将其推入Queue Then have the Queue processing thread quit when it gets the value: 然后让Queue处理线程在获取值时退出:

while True:

    item = request_queue.get()

    if item is None:
        break

    # process the Queue as per normal...

Since the blocking thread is not the main thread, you could also set .daemon = True . 由于阻塞线程不是主线程,您还可以设置.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)

This problem can still occur if Queue.get() is called in the main thread - so the setDaemon(True) answer is not a universal solution. 如果在主线程中调用Queue.get(),则仍会出现此问题 - 因此setDaemon(True)答案不是通用解决方案。

For example this script cannot be stopped with Ctrl-C 例如,无法使用Ctrl-C停止此脚本

#!/usr/bin/python
import Queue

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

Rather than putting a timeout on Queue.get() and dealing with exceptions, a simple solution is to do a wait loop until something is there. 不是在Queue.get()上设置超时并处理异常,而是一个简单的解决方案是进行等待循环直到有东西存在。 This script can be killed with Ctrl-C 可以使用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