Writing multithreaded applications with ZeroMQ

ZeroMQ threads are native threads, which means they are OS threads instead of green threads. The difference between native threads and green threads is that the latter run on user space whereas the former run on kernel space. The main disadvantage of green threads is that the OS has no clue what is going on since these kinds of threads do not rely on the operating system.

There are a few things you need to keep in mind when programming multithreaded applications with ZeroMQ:

  • As mentioned in the previous chapters, ZeroMQ sockets are not thread safe. Therefore, you should not share sockets between threads.
  • Only ZeroMQ context is thread safe.
  • Do not access the same messages from different threads.

The following is a sample multithreaded "Hello world" server using pthread.

#include "czmq.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>


void* worker(void* ctx) {
  zctx_t* context = ctx;
  void* receiver = zsocket_new(context, ZMQ_REP);
  zsocket_connect(receiver, "inproc://workers");

  for(;;) {
    char* str = zstr_recv(receiver);
    printf("Received: %s
", str);
    free(str);

    zclock_sleep(10);
    zstr_send(receiver, "world");
  }

  zsocket_destroy(context, receiver);
  zmq_close(receiver);
  return NULL;
}


int main (int argc, char const *argv[]) {
  
  zctx_t* context = zctx_new();
  void* clients = zsocket_new(context, ZMQ_ROUTER);
  zsocket_bind(clients, "tcp://*:4040");
  void* workers = zsocket_new(context, ZMQ_DEALER);
  zsocket_bind(workers, "inproc://workers");
  
  int i;
  for(i = 0; i < 5; i++) {
    pthread_t thread;
    pthread_create(&thread, NULL, worker, context);
  }
  zclock_sleep(10);
  
  zctx_destroy(&context);
  return 0;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.188.16