Signal-Slot Implementation — Part 3

C. Burak Ongay
brakulla
Published in
2 min readMay 15, 2019

In our previous post, we implemented a producer consumer queue to introduce inter-thread communication. We know how to pass data to another thread to be processed, now we can use this knowledge to provide inter-thread communication with signal-slot mechanism.

The problem is that, there is no way to block all signals or slots look for a conditional variable notification because we don’t have any thread related operation. We need one!

To achieve this thread related functionalities, I’ll introduce a new base class to be inherited by other classes using signal or slot objecs. This class will run in a separate thread with RAII concept, and will provide the threading basis to signal slot mechanism.

Consider that you are emitting a signal from any thread. In order the slot to be run in its own (or its parent’s, I’ll explain in a bit) thread, it should have a thread. This thread can wait on a conditional variable just like the producer consumer queue, until there is an event on its queue. This event is the slot function to be run when a signal emitted.

Okay, it got a little bit confusing, let me explain it with code.

This class will create a new thread on initialization and will keep on running with its run() function. In run function, just as we do in producer consumer thread, we will wait for conditional variable notification. This conditional variable will be notified when addEvent() function is used. Since we want this thread to be run until destroyed, we are using a while loop in run() function. We defined addEvent() function to accept an std::function object as parameter. So when a signal is emitted, it can pass its registered slot functions to this function as to be called. Almost the same as the producer consumer queue, just handling the queue itself with std::function parameter.

Now, you can create class of your own, inherit this threaded class, and use signal or slot objects with compositon. We created the threading basis for our signal slot mechanism. Now we can improve our signal and slot classes to be compatible to work with this.

--

--