Promise and Future: Return a Notification

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

If you 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 I present you 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 a condition variable to a promise and future is that you can use condition variables to synchronize threads multiple times. In contrast to that, a promise can send its notification only once, so you have to use more promise and future pairs to get the functionality of a condition variable. If you 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.

Do you 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 1000+ tech skills courses.