3

I'm using the zmqpp C++ binding of ZeroMQ for building a PUB/SUB communication.

On the subscriber side, there are 2 threads -- mainThread and pollingThread.

pollingThread contains a blocking call to zmqpp::poller::poll(zmqpp::poller::wait_forever).

How, from wihin mainThread, can I interrupt/cancel pollingThread's call to poll() ?

EDIT1: I'm using std::thread, so I can't interrupt the thread.

EDIT2: Here's basically pollingThread's function.

void pollingThread()
{
    while (threadCanRun())
    {
        // wait indefinitely for a new message
        if (mySocketPoller->poll())
        {
            functionToCallWhenAMessageArrives();
        }
    }
}
maddouri
  • 3,737
  • 5
  • 29
  • 51
  • 1
    Can you elaborate on why you chose `zmqpp::poller::wait_forever`? – Drew Dormann Aug 20 '15 at 21:39
  • 1
    Yes. I want to call a particular function only when a new message is broadcast by the publisher. Please check out the edited post for the basic code of `pollingThread`. – maddouri Aug 20 '15 at 21:49

1 Answers1

2

The recommend way would, IMO, be to rely on message passing to handle this.

That would mean:

  1. create a pair of INPROC PAIR socket. One per thread. Connect them.
  2. on the polling thread, also poll() on your PAIR socket.
  3. when you want to interrupt the polling thread, send a message from your PAIR socket to the PAIR socket of the polling thread.
  4. The call to poll() will then return.

Note that this solution, while recommended, will require you to change bits of your code.

    if (mySocketPoller->poll())
    {
        if (mySocketPoller->has_input(my_pair_socket))
        {
         // interrupted.
        }
        functionToCallWhenAMessageArrives();
    }
Xaqq
  • 4,308
  • 2
  • 25
  • 38