I'm solving a exercise using ZeroMQ with Push/Pull pattern where the consumer should push the result, through a different pipe, to the producer. I have the following example:

'use strict';
const cluster = require('cluster');
const fs = require('fs');
const zmq = require('zeromq');
const numWorkers = require('os').cpus().length;

if (cluster.isMaster) {
  // master's queue
  const pusher_m = zmq.socket('push').bind('ipc://filer-pp-m.ipc');
  // worker's queue
  const pusher_w = zmq.socket('push').bind('ipc://filer-pp-w.ipc');

  // Forward product to workers's queue
  for (let i = 0; i < 5; i++) {
    pusher_w.send(
      JSON.stringify({
        task: 'code'
      })
    );
  }

  // Event pull (master consumes master's queue)
  const puller_m = zmq.socket('pull').connect('ipc://filer-pp-m.ipc');
  puller_m.on('message', data => {
    const consumer = JSON.parse(data);
    console.log(`Worker's status: ${consumer.status}`);
  });

  // setup: initialize workers

  cluster.on('online',
    worker => console.log(`Worker ${worker.process.pid} is online.`));

  for (let i = 0; i < numWorkers; i++) {
    cluster.fork();
  }

} else {

  // Event pull (worker consumes worker's queue)
  const puller_w = zmq.socket('pull').connect('ipc://filer-pp-w.ipc');
  puller_w.on('message', data => {
    const consumer = JSON.parse(data);
    console.log(`Worker's task is ${consumer.task}`);
  });

  // Forward result to master's queue)
  const pusher_m = zmq.socket('push').connect('ipc://filer-pp-m.ipc');
  pusher_m.send(
    JSON.stringify({
      status: 'ready'
    })
  );
}

I still need to add more code to make it works/flows as expected. But, right now, I'm trying to solve the problem of pushing back the result from the worker (child process) to the producer (master process), as you can see on the output.

// output
/*
Worker 4341 is online.
Worker 4347 is online.
Worker 4346 is online.
Worker 4353 is online.
Worker's task is code
Worker's task is code
Worker's task is code
Worker's task is code
Worker's task is code
*/

I tried, for testing purpose, to bind the worker's socket inside the Worker's conditional-block (e.g else), and it seems that the producer (master) was able to pull one message from the master's queue. But I believe that is not correct, as the master seems to be the stable process to hold the binding sockets.

Can any one help me? Any doubts, just ask on comments.

0 Answers