python - Python3队列: When can a blocking wait with no timeout return None?

标签 python multithreading python-3.x queue

我想知道何时在python3队列上没有超时的阻塞获取可以返回None。

python3 queue documentation指出:

Queue.get(block=True, timeout=None)

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).



对我来说,这意味着不带参数的get()将等待队列中的某个元素并仅返回该元素,因此始终将返回一个非None的值。仍然在queue documentation底部的示例中,给出了以下代码:
while True:
    item = q.get()
    if item is None:
        break
    ...

对该项目的显式检查是否为None意味着可以返回None。在什么情况下会发生这种情况?

最佳答案

通常,以干净的方式正确结束线程是多线程程序中的一个重要问题。

当线程之间的主要通信 channel 是队列(使用线程通常在调用get()时阻塞该队列)时,一种好的方法是使用通常不会作为数据出现的值来表示不再有更多数据排队,并且使用者线程应该退出。

生产者线程:

with open('/run/myapp/datapipe', 'r') as f:
    for line in f:
        queue.put(line)

# signal end of communication with a sentinel value of None
queue.put(None)

# further clean up

使用者线程:
while True:
    line = queue.get()
    if line is None:
        # if sentinel value was found, break and clean up
        queue.task_done()
        break

    # process line here
    queue.task_done()

# clean up

如果None可以作为正常数据流的一部分出现,则您还可以提供另一个合适的值作为通信标记的结尾。

另外,如果您有多个使用者线程,则此简单的结束标记排队技术将无法满足要求,因为只有其中一个线程将使标记出队。在这种情况下,您可以使每个使用者线程将标记put()取回队列后再回到队列中,从而将结束标记一一传递给每个使用者线程。

关于python - Python3队列: When can a blocking wait with no timeout return None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43758171/

相关文章:

python - 编写Python或TCL VMD脚本

c++ - glibc 的 '-lmcheck' 选项和多线程

c# - 如何在 C# 中保护 SqlDataReader 免受多次访问

python - 从文件读取并作为字典返回的函数?

python - 如何将列表列表转换为结构化字典,Python3

python - 为什么我的 2D 插值器在 SciPy 中生成一个交换轴的矩阵?

c# - 什么相当于 python 中的 C# 任务

java - java中的中断处理

python - python方法前的减号

python - Pandas - 添加新的聚合功能