Modern Effective C++ - Alternative to condition variables for thread communication

As discussed in the previous article, usage of mutexes and condition variables is problematic especially when we simply want to signal(just once) to the callee. Recall that we can visualize std::future as communication channel between the caller and the callee. The caller end of the communication channel waits on the future, whereas the callee in it's end, writes the results in the channel by simply returning the return value, or by setting  std::promise.

In our example program we were simply using the flag to signal the runners to start running. There was no actual data which was passed. Hence for the sake of signalling we can use std::future<void> and std::promise<void>. But the roles are reversed where we want the caller to signal the callee. Have a look at the program below


The program runs even if you uncomment lines 14, 42.

Here the caller has the promise, which it sets when it's ready, using set_value API. The callee possesses the future (shared future in our case) associated with the caller's promise, and waits on it. Once the caller sets the promise, the callee function threads get signaled via the waiting future and continues it's execution.

In the program, instead of polluting the callee function with thread communication logic, we have separated the communication mechanism, and have put the callee function, and shared future separately in the lambda.

We have used shared future because there are multiple threads are waiting for the condition. However in the previous article I have mentioned that the (regular) future is itself in a shared location. So you might be wondering what's the difference between std::future i.e the regular future and the std::shared_future. Shared future is copyable and hence each thread can wait on it's own shared_future.std::future is not copyable and only moveable.

We can capture std::future by reference, as shown in the below program.

But capturing by reference might lead to dangling references. So we have to be mindful of the scope when using std::future.

The article is inspired by Scott Meyer's Effective Modern C++.


Modern Effective C++ - Alternative to condition variables for thread communication Modern Effective C++ - Alternative to condition variables for thread communication Reviewed by zeroingTheDot on May 25, 2018 Rating: 5

No comments:

Powered by Blogger.