[zeromq-dev] How to reuse a message in zeromq?

Chuck Remes cremes.devlist at mac.com
Mon Aug 1 15:45:29 CEST 2011


On Aug 1, 2011, at 8:16 AM, kaka chen wrote:

> Hi All:
> 
>     From source code of zeromq, I found it writes message to outbound pipe, the ownership is transfered to pipe, and the original message was re-initialized to a empty size message by zmq_msg_init(1). This strategy prevent me to reuse a message for test because I can not manage this message's life-cycle and the pipe will manage it. So I can not test 1M size message for looping 10000 times, it will occur mem allocate problems. Is it has some method to reuse a message in zeromq? what about try to use ref-count when writing message
> to outbound pipe by override operator = () function in message_size_t.

I can tell you haven't read the man pages or the guide yet. There are two ways of accomplishing your goal.

One, take a look at zmq_msg_init_data() [1]. It creates a zmq_msg_t structure and uses the buffer that you pass to it. It also takes an *optional* function pointer to deallocate the buffer when 0mq is done with it. If you leave that as NULL, then 0mq will not deallocate the buffer. Therefore, you could call zmq_msg_init_data() in a tight loop and pass it the same buffer over and over again (zero-copy).

Alternately, you could also use zmq_msg_copy() [2] to copy the data buffer from a "src" message to a new "dst" message. The underlying implementation does *not* do a memcpy(); instead, it increments a reference count. A later call to zmq_msg_close() decrements that count. When the count reaches 0, the deallocation function is called to release the memory.

I highly recommend that you read through the documentation. Your questions are all answered in the guide or in the man pages.

cr

[1] http://api.zeromq.org/2-1:zmq-msg-init-data

[2] http://api.zeromq.org/2-0:zmq-msg-copy



More information about the zeromq-dev mailing list