Promise and Future: Returning a Notification

This lesson teaches us how to return a notification while using std::promise and future in C++.

If we use promises and futures to synchronize threads, they have a lot in common with condition variables. Most of the time, promises and futures are the better choices. Before we present an example, here is the big picture.

Criteria Condition Variables Tasks
Multiple synchronizations Yes No
Critical section Yes No
Error handling in receiver No Yes
Spurious wakeup Yes No
Lost wakeup Yes No

The advantage of using a condition variable over a promise and future is that we can use condition variables to synchronize threads multiple times. In contrast to that, a promise can send its notification only once, so we have to use more promise and future pairs to get the functionality of a condition variable. If we use the condition variable for only one synchronization, the condition variable is a lot more difficult to use in the right way. A promise and future pair needs no shared variable and, therefore, it doesn’t have a lock, and isn’t prone to spurious or lost wakeups. In addition to that, tasks can handle exceptions. There are lots of reasons to prefer tasks to condition variables.

Remember how difficult it was to use condition variables? If not, here are the key parts required to synchronize two threads.

Get hands-on with 1400+ tech skills courses.