LScarpinati

ZMQ multithread example

Oct 6th, 2015
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. //  Multithreaded Hello World server
  2.  
  3. #include "zhelpers.h"
  4. #include <pthread.h>
  5.  
  6. static void *
  7. worker_routine (void *context) {
  8.     //  Socket to talk to dispatcher
  9.     void *receiver = zmq_socket (context, ZMQ_REP);
  10.     zmq_connect (receiver, "inproc://workers");
  11.  
  12.     while (1) {
  13.         char *string = s_recv (receiver);
  14.         printf ("Received request: [%s]\n", string);
  15.         free (string);
  16.         //  Do some 'work'
  17.         sleep (1);
  18.         //  Send reply back to client
  19.         s_send (receiver, "World");
  20.     }
  21.     zmq_close (receiver);
  22.     return NULL;
  23. }
  24.  
  25. int main (void)
  26. {
  27.     void *context = zmq_ctx_new ();
  28.  
  29.     //  Socket to talk to clients
  30.     void *clients = zmq_socket (context, ZMQ_ROUTER);
  31.     zmq_bind (clients, "tcp://*:5555");
  32.  
  33.     //  Socket to talk to workers
  34.     void *workers = zmq_socket (context, ZMQ_DEALER);
  35.     zmq_bind (workers, "inproc://workers");
  36.  
  37.     //  Launch pool of worker threads
  38.     int thread_nbr;
  39.     for (thread_nbr = 0; thread_nbr < 5; thread_nbr++) {
  40.         pthread_t worker;
  41.         pthread_create (&worker, NULL, worker_routine, context);
  42.     }
  43.     //  Connect work threads to client threads via a queue proxy
  44.     zmq_proxy (clients, workers, NULL);
  45.  
  46.     //  We never get here, but clean up anyhow
  47.     zmq_close (clients);
  48.     zmq_close (workers);
  49.     zmq_ctx_destroy (context);
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment