Skip to main content
 首页 » 编程设计

python之远程队列消费者在重启后错过了第一条消息

2025年02月15日13zhujiabin

我有如下代码:

服务器.py

import queue 
from multiprocessing.managers import BaseManager 
 
class QueueManager(BaseManager): 
    pass 
 
q = queue.Queue() 
QueueManager.register('queue', callable=lambda:q) 
m = QueueManager(address=('localhost', 51000), authkey=b'pass') 
s = m.get_server() 
s.serve_forever() 

生产者.py

from multiprocessing.managers import BaseManager 
import time 
 
class QueueManager(BaseManager): 
    pass 
 
QueueManager.register('queue') 
m = QueueManager(address=('localhost', 51000), authkey=b'pass') 
m.connect() 
queue = m.queue() 
 
idx = 0 
while True: 
    time.sleep(2) 
    queue.put(idx) 
    idx += 1 

消费者.py

from multiprocessing.managers import BaseManager 
 
class QueueManager(BaseManager): 
    pass 
 
QueueManager.register('queue') 
m = QueueManager(address=('localhost', 51000), authkey=b'pass') 
m.connect() 
queue = m.queue() 
 
while True: 
    message = queue.get() 
    print(message) 

如果我运行服务器和生产者,然后启动消费者,我会看到生产者放入队列的所有消息都出现在消费者处。但是,如果我停止消费者并立即重新启动它,它总是会跳过一条消息。

为了说明我所看到的 consumer.py 的输出:

0 
1 
2 
3 
<restart the consumer> 
5 
6 
7 
etc. 

这就是 python 多处理队列应该如何工作,这是一个错误还是我做错了什么?

请您参考如下方法:

我认为问题在于 python 中管道的实现方式,或者甚至可能是操作系统的限制。这是完整的堆栈跟踪:

Traceback (most recent call last): 
  File "consumer.py", line 12, in <module> 
    message = queue.get() 
  File "<string>", line 2, in get 
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/managers.py", line 757, in _callmethod 
    kind, result = conn.recv() 
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 250, in recv 
    buf = self._recv_bytes() 
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 407, in _recv_bytes 
    buf = self._recv(4) 
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 379, in _recv 
    chunk = read(handle, remaining) 
KeyboardInterrupt 

该值似乎在 queue.get() 调用中丢失,该调用未使用 SIGINT 正确终止。 queue.get() 立即被取消,因此 python 不会完成 get() 调用然后丢失值。看起来更像是 python 没有正确取消管道上的 recv。

如果您要将消费者更改为:

while True: 
    while queue.empty(): 
        sleep(0.1) 
    message = queue.get() 
    print(message) 

它会起作用的。但这当然是一种变通方法,而不是真正的解决方案。

更新:

在仔细研究了您的代码之后,我认为这是一个错误,因为:

  1. 你followed their coding example one by one
  2. 没有一种队列可以解决问题(multiprocessing.Queue 和 multiprocessing.JoinableQueue
  3. 同时发送 task_done() 也无济于事

该错误同时发生在 python2 和 python3 上。我建议你report this as a bug .在最坏的情况下,如果这不是错误,您至少会得到一个解释,为什么 python 会这样做。