[英]Python zeromq — Multiple Publishers To a Single Subscriber?
我想編寫一個python
腳本(稱為parent ),它執行以下操作:
(1)定義一個多維numpy
數組
(2) forks
10 個不同python
腳本(稱它們為children )。 它們中的每一個都必須能夠在任何單個時間點(只要它們還活着)從(1) read
numpy
數組的內容。
(3)每個子腳本都會做自己的工作(孩子們不要互相分享任何信息)
(4)在任何時間點,父腳本必須能夠接受來自其所有子腳本的消息。 這些消息將由父級解析並導致(1)中的numpy
數組發生更改。
在Linux
環境中在python
中工作時,我該如何處理這個問題? 我想使用zeroMQ
並讓父級是單個訂閱者,而子級都是發布者; 這有意義還是有更好的方法?
另外,如何讓所有子級連續讀取父級定義的numpy
數組的內容?
sub
頻道不一定是要綁定的頻道,因此您可以綁定訂閱者,並且每個子pub
頻道都可以連接到該頻道並發送他們的消息。 在這種特殊情況下,我認為multiprocessing
模塊更合適,但我認為它值得一提:
import zmq
import threading
# So that you can copy-and-paste this into an interactive session, I'm
# using threading, but obviously that's not what you'd use
# I'm the subscriber that multiple clients are writing to
def parent():
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, 'Child:')
# Even though I'm the subscriber, I'm allowed to get this party
# started with `bind`
socket.bind('tcp://127.0.0.1:5000')
# I expect 50 messages
for i in range(50):
print 'Parent received: %s' % socket.recv()
# I'm a child publisher
def child(number):
context = zmq.Context()
socket = context.socket(zmq.PUB)
# And even though I'm the publisher, I can do the connecting rather
# than the binding
socket.connect('tcp://127.0.0.1:5000')
for data in range(5):
socket.send('Child: %i %i' % (number, data))
socket.close()
threads = [threading.Thread(target=parent)] + [threading.Thread(target=child, args=(i,)) for i in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
特別是,文檔的核心消息傳遞模式部分討論了對於模式,任何一方都可以綁定(和另一方連接)的事實。
我認為使用 PUSH/PULL sockets 更有意義,因為您有一個標准的Ventilator - Workers - Sink場景,除了 Ventilator 和 Sink 是相同的過程。
另外,考慮使用多處理模塊而不是 ZeroMQ。 可能會容易一些。
在 ZeroMQ 中,每個端口只能有一個發布者。 唯一(丑陋的)解決方法是在不同的端口上啟動每個子 PUB 套接字,並讓父級監聽所有這些端口。
但是 0MQ 上描述的管道模式,用戶指南是一種更好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.