Chapter 7. The Concurrency API
One of C++11âs great triumphs is the incorporation of concurrency into the language and library. Programmers familiar with other threading APIs (e.g., pthreads or Windows threads) are sometimes surprised at the comparatively Spartan feature set that C++ offers, but thatâs because a great deal of C++âs support for concurrency is in the form of constraints on compiler writers. The resulting language assurances mean that for the first time in C++âs history, programmers can write multithreaded programs with standard behavior across all platforms. This establishes a solid foundation on which expressive libraries can be built, and the concurrency elements of the Standard Library (tasks, futures, threads, mutexes, condition variables, atomic objects, and more) are merely the beginning of what is sure to become an increasingly rich set of tools for the development of concurrent C++ software.
In the Items that follow, bear in mind that the Standard Library has two templates for futures: std::future
and std::shared_future
. In many cases, the distinction is not important, so I often simply talk about futures, by which I mean both kinds.
Item 35:âPrefer task-based programming to thread-based.
If you want to run a function doAsyncWork
asynchronously, you have two basic choices. You can create a std::thread
and run doAsyncWork
on it, thus employing a thread-based approach:
int doAsyncWork();
std::thread t(doAsyncWork);
Or you can pass doAsyncWork
Get Effective Modern C++ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.