March 2013
Intermediate to advanced
516 pages
15h 11m
English
Example 3-2 is an example of the load-balancing pattern using a ROUTER broker talking to a set of REQ workers.
Example 3-2. ROUTER-to-REQ (rtreq.c)
//// ROUTER-to-REQ example//#include "zhelpers.h"#include <pthread.h>#define NBR_WORKERS 10staticvoid*worker_task(void*args){void*context=zmq_ctx_new();void*worker=zmq_socket(context,ZMQ_REQ);s_set_id(worker);// Set a printable identityzmq_connect(worker,"tcp://localhost:5671");inttotal=0;while(1){// Tell the broker we're ready for works_send(worker,"Hi Boss");// Get workload from broker, until finishedchar*workload=s_recv(worker);intfinished=(strcmp(workload,"Fired!")==0);free(workload);if(finished){printf("Completed: %d tasks\n",total);break;}total++;// Do some random works_sleep(randof(500)+1);}zmq_close(worker);zmq_ctx_destroy(context);returnNULL;}
While this example runs in a single process, that is only to make it easier to start and stop. Each thread has its own context and conceptually acts as a separate process. Example 3-3 shows the main task.
Example 3-3. ROUTER-to-REQ (rtreq.c): main task
intmain(void){void*context=zmq_ctx_new();void*broker=zmq_socket(context,ZMQ_ROUTER);zmq_bind(broker,"tcp://*:5671");srandom((unsigned)time(NULL));intworker_nbr;for(worker_nbr=0;worker_nbr<NBR_WORKERS;worker_nbr++){pthread_tworker;pthread_create(&worker,NULL,worker_task,NULL);}// Run for five seconds ...
Read now
Unlock full access