I am trying to use zeroMQ as a way to implement a messaging system between multiple threads. I tried the code below but it doesn't work; in the specific the call to zmq_recv in each thread doesn't wait/block for any message to be executed.
Can you help me with this piece of code?
I am using Linux OS and gcc
Best Regards
AFG
static void *
worker_routine (void *context) {
// Socket to talk to dispatcher
void *receiver = zmq_socket (context, ZMQ_REP);
zmq_connect (receiver, "inproc://workers");
while (1) {
zmq_msg_t request;
zmq_msg_init( &request );
zmq_recv( receiver, &request, 0 );
printf ("Received request\n");
// Do some 'work'
usleep (1000);
// Send reply back to client
zmq_send (receiver, &request, 0);
}
zmq_close (receiver);
return NULL;
}
int main (void) {
void *context = zmq_init (1);
void *clients = zmq_socket (context, ZMQ_REP);
zmq_bind (clients, "inproc://workers");
int thread_nbr;
for (thread_nbr = 0; thread_nbr < 5; thread_nbr++) {
pthread_t worker;
pthread_create (&worker, NULL, worker_routine, context);
}
zmq_close (clients);
zmq_term (context);
return 0;
}
Both sockets are REP. What you want is REQ + REP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With