我正在使用 ZeroMQ 来实现玩具通信协议(protocol);这是我第一次使用这个框架/库。
现在,在我的协议(protocol)中,某一方发送多条连续消息,所有消息都具有相同的大小。所以 - 我想,我会避免重新分配它们,而只是尝试用不同的内容重新填充消息数据缓冲区,例如:
zmq::message_t msg { fixed_common_size };
while (some_condition()) {
my_filling_routine(msg.data(), fixed_common_size);
the_socket.send(msg);
}
但是在这个循环的第二次迭代中,我遇到了段错误;但 msg.data()
不是 nullptr
。我突然想到,ZeroMQ 可能会以某种方式蚕食内存,因此我需要编写如下内容:
zmq::message_t msg { fixed_common_size };
char buffer[fixed_common_size];
while (some_condition()) {
my_filling_routine(buffer, fixed_common_size);
msg.rebuild(buffer, fixed_common_size);
the_socket.send(msg);
}
但我确信这会导致取消分配和重新分配。
那么,rebuild()
确实是必要的,还是可能只是我的代码中的一些错误?
注意:我正在使用 Unix 套接字,以防答案以某种方式依赖于此。
最佳答案
不可以,zmq::message_t
发送后无法重复使用。
首先,欢迎来到 ZeroMQ,这是一个很酷的地方 distributed-system从业者。
ZeroMQ API 非常明确地警告这些问题。成功调用 zmq_msg_send()
(引用消息有效负载)并不意味着消息本身已实际发送。
最好尝试想象调用只是将责任从应用程序代码“转移”到 ZeroMQ 引擎(在工厂内部,在 中实例化了 IO 线程池) Context()
-实例...)。
The
zmq_msg_t
structure passed tozmq_msg_send()
is nullified during the call.
接下来更好的是永远不要稍后再按上面报告的那样触摸它:o)
分配器的最大“生态”绕过是重用整个消息,如下:
If you want to send the same message to multiple sockets you have to copy it using ( e.g. using
zmq_msg_copy()
).
关于复制的额外警告...
再加一个提点:可以复制,但以后敢尝试修改...
Avoid modifying message content after a message has been copied with
zmq_msg_copy()
, doing so can result in undefined behaviour. If what you need is an actual hard copy, allocate a new message usingzmq_msg_init_size()
and copy the message content usingmemcpy()
.
Never accesszmq_msg_t
members directly, instead always use thezmq_msg
-family of functions.
关于segmentation-fault - zmq::message_t发送后可以重复使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50088894/