[zeromq-dev] Communication between two threads

Martin Sustrik sustrik at 250bpm.com
Fri Mar 19 15:28:06 CET 2010

On 19/3/2010, "gonzalo diethelm" <gdiethelm at dcv.cl> wrote:

>> I've got lost in the scenario :) Can you write down few points showing
>> step-by-step what your application should do?
>Ok, sorry for the rant. It is like this.
>My process will have two threads. One of them, called "poller", owns and
>has several sockets open, and issues an infinite poll() loop on all of
>them. This way I can react to incoming requests, to notifications the
>process is subscribed to, etc.
>The second thread, called "runner", does "real work". It is computing
>things, reading / writing to a DB, etc.
>Some times I need to send a message, from the runner thread, over one of
>my sockets in the poller thread. This is because I want to notify
>another process about something, or I want to request some information
>from an external process.
>Since poller and runner are separate threads, and I can only use the
>sockets in the poller thread, I thought about doing this:
>1. Add an inproc REP socket, called "pipe", to the poller thread, and
>put it in the poll loop.
>2. Add an inproc REQ socket to the runner thread, connected to "pipe".
>3. When the runner thread needs to fire off a message, it writes it to
>its inproc REQ socket and busy-waits for a reply.
>4. The poll loop wakes up in the poller thread, reads a message from the
>inproc REP socket, sends it over the "real" outgoing socket, waits for a
>reply and sends this reply back over the inproc REP socket.
>5. The runner thread receives its answer back and goes merrily about
>working with it.
>Besides allowing me to do all external communications from a single
>thread, this setup neatly solves the synchronization between the two

Yes, it looks sensible. Go for it.


More information about the zeromq-dev mailing list