Member-only story
Writing Framework for Inter Thread Message Passing in C++
A framework for passing messages between threads without having to worry about low-level threading code
Inter-thread Message Passing in C++
Overview
In many cases, developers have to deal with multi-threading when developing applications. When dealing with multiple threads, we almost certainly need to synchronize them, and one of the synchronization methods is message passing.
In this article, I will start with implementing inter-thread message passing in C++ using the standard library, followed by presenting the implementation issues, and finally showing how to write a simple framework to make our code more elegant.
Thread Sync with Mutex
I’m sure you’re all familiar with mutexes, the synchronization primitives we use to prevent shared resources or shared objects from being accessed simultaneously by multiple threads causing a condition called a race condition.
One simple example is a thread that is supposed to modify an int
, and the other is to print it if the value is non-zero and set it to zero afterward. In C++, we can implement this simple example by using std::thread
and std::mutex
as shown in the following code.
We have two threads, producer
and consumer
whose runtime is controlled by the OS where this application is running on. Both threads must acquire count_mutex
before accessing count
. We can’t easily predict the outcome of this code because the scheduling of both threads is controlled by the OS.
One issue you might notice with this locking mechanism is that both threads have to constantly check if the shared resource count
is ready to be used, which wastes CPU cycles that could otherwise be used for other purposes.
We have already solved our issue of preventing race conditions, but this solution isn’t very efficient…