Book Image

ZeroMQ

By : Faruk Akgul
Book Image

ZeroMQ

By: Faruk Akgul

Overview of this book

<p>ØMQ (also spelled ZeroMQ, 0MQ, or ZMQ) is a high-performance asynchronous messaging library aimed at use in scalable distributed or concurrent applications. It provides a message queue, but unlike message-oriented middleware, a ØMQ system can run without a dedicated message broker. The library is designed to have a familiar socket-style API.<br /><br />"ZeroMQ" teaches you to use ZeroMQ through examples in C programming language. You will learn how to use fundamental patterns of message/queuing with a step-by-step tutorial approach and how to apply them. Then, you’ll learn how to use high level APIs and to work with multiple sockets and multithreaded programs through many examples.<br /><br />This book looks at how message/queue works in general and what kinds of problems it solves. Then, it explains how ZeroMQ works and how it differs from other message/queue libraries and how it can be used in different scenarios.<br /><br />You will also learn how to apply essential message/queue design patterns in different scenarios, and how they differ from each other. It shows you practical examples you can apply. You will also learn how to work with multiple sockets.<br /><br />You will learn the basics of ZeroMQ as well as how to use different patterns.</p>
Table of Contents (12 chapters)

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...