我正在尝试使用队列将数据发送到多处理进程。由于某种原因,该示例不起作用。你知道为什么吗?
我希望程序打印出“Received something: hello”和“Received poison pill”,但它永远不会到达那里。但是,它确实会打印“running”和“listening”,所以我知道它肯定会尝试从队列中读取一些内容。
我正在使用 Pythong 3.4
from multiprocessing import Process
import queue
import time
class EventAggregatorProcess(Process):
def __init__(self):
super(EventAggregatorProcess, self).__init__()
self.event_queue = queue.Queue()
def run(self):
print('running')
is_stopped=False
while not is_stopped:
print('listening')
msg = self.event_queue.get()
if msg:
print('Received something: %s'%msg)
else:
print( 'Received poison pill' )
is_stopped=True
if __name__=='__main__':
eap = EventAggregatorProcess()
eap.start()
time.sleep(1)
eap.event_queue.put('hello')
eap.event_queue.put(None)
请您参考如下方法:
queue模块用于多线程程序。这些线程都在一个进程中,这意味着它们也共享内存。 (请参阅 docs 末尾的另请参阅部分)您的程序是 multiprocessing,这意味着您有多个进程。这些进程不共享内存。你应该使用 Queue来自 multiprocessing 库。此版本的 Queue 处理进程间通信所需的额外工作。
from multiprocessing import Process, Queue
