Chapter 4. Synchronizing concurrent operations

 

This chapter covers

  • Waiting for an event
  • Waiting for one-off events with futures
  • Waiting with a time limit
  • Using the synchronization of operations to simplify code

In the last chapter, we looked at various ways of protecting data that’s shared between threads. But sometimes you don’t just need to protect the data, you also need to synchronize actions on separate threads. One thread might need to wait for another thread to complete a task before the first thread can complete its own, for example. In general, it’s common to want a thread to wait for a specific event to happen or a condition to be true. Although it would be possible to do this by periodically checking a “task complete” flag or something similar stored in shared data, this is far from ideal. The need to synchronize operations between threads like this is such a common scenario that the C++ Standard Library provides facilities to handle it, in the form of condition variables and futures. These facilities are extended in the Concurrency Technical Specification (TS), which provides additional operations for futures, alongside new synchronization facilities in the form of latches and barriers.

In this chapter, I’ll discuss how to wait for events with condition variables, futures, latches, and barriers, and how to use them to simplify the synchronization of operations.

4.1. Waiting for an event or other condition

4.2. Waiting for one-off events with futures

4.3. Waiting with a time limit

4.4. Using synchronization of operations to simplify code

Summary

sitemap