pyzmq的PUB / SUB模型没有在multiprocessing.Process中接收消息

时间:2017-10-12 12:24:20

标签: python python-3.x multiprocessing zeromq pyzmq

我正在尝试在 PUB/SUB 领域内使用pyzmq multiprocessing.Process 套接字原型:

我有一个订阅者:

import time
import collections    
import zmq

context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b"")
socket.connect("tcp://localhost:5000")

nb_recv = 0
begin = time.time()
counter = collections.defaultdict(int)
while True:
    msg = socket.recv_json()
    print(msg)

发布商的两种不同实现。

有了这个,订阅者接收消息:

import zmq
from multiprocessing import Process

class Sender(object):

    def __init__(self):
        self._context = zmq.Context()
        pass

    def run(self):
        self._socket = self._context.socket(zmq.PUB)
        self._socket.bind("tcp://127.0.0.1:5000")
        seq_num = 0
        while True:
            msg = { "sequence": seq_num }
            self._socket.send_json(msg)
            seq_num += 1

if __name__ == "__main__":
    s = Sender()
    p = Process(target=s.run)
    p.start()
    p.join()

但是这个(唯一的区别是 socket 的创建在构造函数中,而不是在 run() 类方法),订阅者不接收任何消息:

import zmq
from multiprocessing import Process

class Sender(object):

    def __init__(self):
        self._context = zmq.Context()
        self._socket = self._context.socket(zmq.PUB) # <---------
        pass

    def run(self):
        self._socket.bind("tcp://127.0.0.1:5000")
        seq_num = 0
        while True:
            msg = { "sequence": seq_num }
            self._socket.send_json(msg)
            seq_num += 1

if __name__ == "__main__":
    s = Sender()
    p = Process(target=s.run)
    p.start()
    p.join()

当我用 multiprocessing.Process 替换threading.Thread时,这两个类都运行良好,但我没有找到有关文档的任何解释。

1 个答案:

答案 0 :(得分:0)

您在一个进程中创建对象并尝试在另一个进程中执行该方法。

{em} 可能create甚至sharepackage yyy.yyy.yyy.yyy.models; import android.content.Context; import yyy.yyy.yyy.yyy.database.dbConnection; import java.io.Serializable; public class CategoriesModel extends dbConnection implements Serializable { private int id; private String title; public CategoriesModel(Context context) { super(context); } public void setId(int id) { this.id = id; } public void setTitle(String title) { this.title = title; } public int getId() { return id; } public String getTitle() { return title; } } 进程与multiprocessing之间的对象,但由于此对象拥有不可共享的资源(网络套接字),你最好在工作进程中创建它,除非你想走在酸洗的雷区和使用具有不可选择字段的对象。