ZeroMQ Pub/Sub 仅在订阅主题时丢弃消息

ZeroMQ Pub/Sub drops messages only when subscribing to topics

我只有在订阅主题时才会丢失消息。

场景如下:
订阅者订阅特定主题,然后在不同的线程中调用发布者(具有相同的上下文和相同的"subscribed topic")。
发布者收到 "subscribed topic" 并发布它。

当我 运行 两个过程(意味着 2 个订阅者线程和 2 个发布者线程)时,我在其中一个线程上只收到一条消息(随机)。
我不知道为什么我会丢失第二条消息。

发布者线程:

void *publisher = zmq_socket(ptStruct->zContext, ZMQ_PUB);
assert(0 == zmq_bind(publisher, "inproc://#1"));
printf("Publishes to %d \n", ptStruct->iID);
assert(-1 != zmq_send(publisher, &(ptStruct->iID), sizeof(ptStruct->iID), 0));
zmq_close(publisher);

订阅者线程:

void *subscriber = zmq_socket(ptStruct->zContext, ZMQ_SUB);
assert(0 == zmq_connect(subscriber, "inproc://#1"));
assert(0 == zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, &(ptStruct->iID), sizeof(ptStruct->iID)));
printf("Subscribed to %d \n", ptStruct->iID);

/* Now run the publisher in a different thread */
OSTHREAD_CreateThread(&ptThread, publishThread, ptStruct, NULL);

assert(-1 != zmq_recv(subscriber, acRec, 255, 0));
printf("Got %d \n", acRec[0]);
zmq_close(subscriber);

我运行订阅者线程两次,这是输出:

Subscribed to 1
Subscribed to 2
Publishes to 1
Got 1
Publishes to 2

您正在创建两个不同的发布者,它们 bind()-ing 到同一个 inproc 端点“#1”——一个端点只能绑定一次,第二个发布者失败bind() 在同一终结点上,然后不发送消息。

此外,由于 slow joiner 问题,您可能希望在发布者 bind()-ing 和 send()-ing 第一条消息之间添加一些延迟 -发布者可能会在发布者和订阅者完成连接之前尝试发送然后丢弃您的消息,这也会导致您丢失消息。