[zeromq-dev] Thread Safe sockets

Martin Sustrik sustrik at 250bpm.com
Tue Feb 7 09:55:23 CET 2012


On 02/07/2012 05:41 PM, Nadav Samet wrote:

> I'm not sure I follow, what's evil about callbacks? In particular, I am
> working on an RPC library on top of ZeroMQ. It spawns n threads, and
> whenever a request arrives it runs a user-supplied function (i.e.
> callback) on one of these threads. Are there alternative designs that I
> should consider?

The main reason for recv() being better than callbacks is that it 
produces cleaner and more maintainable code.

Imagine an REQ/REP application that sends 10 requests and receives 10 
replies.

Using recv() the code look pretty straightforward:

s = socket (REQ);
while (i = 0; i != 10; i++) {
     s.send (request);
     s.recv (&reply);
}

Now consider how the same thing looks like when using callbacks:

static int i = 0;
semaphore sem;

callback (reply)
{
     i++;
     if (i = 10) {
         sem.post ();
     else
         s.send (request);
}

main ()
{
     s = socket (REQ, callback);
     s.send (request);
     sem.wait ();
}

How readable is that? And what about the global variables? etc.

Martin



More information about the zeromq-dev mailing list