Quantcast
Channel: Active questions tagged zeromq - Stack Overflow
Viewing all articles
Browse latest Browse all 193

ZeroMQ (C++): sending pointer with inproc

$
0
0

I am trying out ZeroMQ (zmq) for the multithreaded program.I want to avoid copying the data that need to be passed to workers.My idea was to send the pointer to the data as a zmq message.It works. But I discovered that if I change the data inside the worker, the producer (main) does not see it. I wonder why!

Here is an example:

#include <cstring>#include <iostream>#include <memory>#include <thread>#include <zmq.h>struct Foo {  explicit Foo(int value) noexcept  : _value{value}   {}  int _value;};void worker(void *context){  void *receiver = zmq_socket(context, ZMQ_REP);  zmq_connect(receiver, "inproc://example");  std::this_thread::sleep_for(std::chrono::milliseconds(20));  zmq_msg_t message;  zmq_msg_init(&message);  zmq_msg_recv(&message, receiver, 0);  char received[sizeof(Foo *)];  std::memcpy(&received, zmq_msg_data(&message), sizeof(Foo *));  //reinterpret_cast<Foo *>(received)->_value = 111;  std::cout << "Received Foo with value: " << reinterpret_cast<Foo *>(received)->_value << std::endl;  std::cout << "   the address of value: " << std::addressof(reinterpret_cast<Foo *>(received)->_value) << std::endl;  zmq_msg_close(&message);  zmq_close(receiver);}int main(){  void *context = zmq_ctx_new();  void *sender = zmq_socket(context, ZMQ_REQ);  zmq_bind(sender, "inproc://example");  std::jthread thread{worker, context};  auto foo{ std::make_unique<Foo>(42) };  std::cout << "Sending Foo with value : " << foo->_value << std::endl;  std::cout << "   the address of value: " << std::addressof(foo->_value) << std::endl;  zmq_msg_t message;  zmq_msg_init_size(&message, sizeof(Foo *));  std::memcpy(zmq_msg_data(&message), foo.get(), sizeof(Foo *));  zmq_msg_send(&message, sender, 0);  zmq_msg_close(&message);  zmq_close(sender);  zmq_ctx_destroy(context);  return 0;}

The output I get is

Sending Foo with value : 42   the address of value: 0x55a8c6fe2a90Received Foo with value: 42   the address of value: 0x7f30c0a52d40

As you can see, the addresses of _value are different, so that explains why changing the value inside the worker does not affect the producer. But I don't understand why they are different.

Lastly, is this even the right approach to send data without copying it via inproc transport?


Viewing all articles
Browse latest Browse all 193

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>