Language-Level Concurrency and Parallelism in C++
C++ has had excellent support for concurrent programming ever since the C++ 11 language standard came out. Until then, threading was an affair that was handled by platform-specific libraries. The Microsoft Corporation had its own threading libraries, and other platforms (GNU Linux/macOS X) supported the POSIX threading model. A threading mechanism as part of the language has helped C++ programmers write portable code that runs on multiple platforms.
The original C++ standard was published in 1998, and the language design committee firmly believed that threading, filesystems, GUI libraries, and so on are better left to the platform-specific libraries. Herb Sutter published an influential article in the Dr. Dobbs Journal titled, The Free Lunch Is Over, where he advocated programming techniques to exploit multiple cores available in the processors of those days. While writing parallel code, functional programming models are well-suited for the task. Features such as threads, Lambda functions and expressions, move semantics, and memory guarantee helps people write concurrent or parallel code without much hassle. This chapter aims to enable developers to leverage thread libraries and their best practices.
In this chapter, we will cover the following topics:
- What is concurrency?
- A characteristic Hello World program using multiple threads
- How to manage the lifetime and resources of threads
- Sharing data between threads
- How to write a thread-safe data structure