March 2013
Intermediate to advanced
516 pages
15h 11m
English
When you start making multithreaded applications with ØMQ, you’ll encounter the question of how to coordinate your threads. Though you might be tempted to insert “sleep” statements, or use multithreading techniques such as semaphores or mutexes, the only mechanism that you should use is ØMQ messages. Remember the story of the drunkards and the beer.
Let’s make three threads that signal each other when they are
ready (Figure 2-13). In Example 2-12, we
use PAIR sockets over the inproc
transport.
Example 2-12. Multithreaded relay (mtrelay.c)
//// Multithreaded relay//#include "zhelpers.h"#include <pthread.h>staticvoid*step1(void*context){// Connect to step2 and tell it we're readyvoid*xmitter=zmq_socket(context,ZMQ_PAIR);zmq_connect(xmitter,"inproc://step2");printf("Step 1 ready, signaling step 2\n");s_send(xmitter,"READY");zmq_close(xmitter);returnNULL;}staticvoid*step2(void*context){// Bind inproc socket before starting step1void*receiver=zmq_socket(context,ZMQ_PAIR);zmq_bind(receiver,"inproc://step2");pthread_tthread;pthread_create(&thread,NULL,step1,context);// Wait for signal and pass it onchar*string=s_recv(receiver);free(string);zmq_close(receiver);// Connect to step3 and tell it we're readyvoid*xmitter=zmq_socket(context,ZMQ_PAIR);zmq_connect(xmitter,"inproc://step3");printf("Step 2 ready, signaling step 3\n");s_send(xmitter,"READY");zmq_close(xmitter);
Read now
Unlock full access