Concurrency with Modern C++
Concurrency with Modern C++
What every professional C++ programmer should know about concurrency.
About the Book
Concurrency with Modern C++ is a journey through current and upcoming concurrency in C++.
- C++11 and C++14 have the basic building blocks for creating concurrent or parallel programs.
- With C++17 we got the parallel algorithms of the Standard Template Library (STL). That means, most of the algorithms of the STL can be executed sequential, parallel, or vectorized.
- The concurrency story in C++ goes on. With C++20/23 we can hope for executors, extended futures, coroutines, transactions, and more.
This book explains you the details to concurrency in modern C++ and gives you, in addition, more than 100 running code examples . Therefore you can combine the theory with the practices and get the most of it.
Because this book is about concurrency, I present a lot of pitfalls and show you how to overcome them.
Reader Testimonials
Bart Vandewoestyne
Senior Development Engineer Software at Esterline
'Concurrency with Modern C++' is your practical guide to getting familiar with concurrent programming in Modern C++. Starting with the C++ Memory Model and using many ready-to-run code examples, the book covers a good deal of what you need to improve your C++ multithreading skills. Next to the enlightening case studies that will bring you up to speed, the overview of upcoming concurrency features might even wet your appetite for more!
Ian Reeve
Senior Storage Software Engineer for Dell Inc.
Rainer Grimm's Concurrency with Modern C++ is a well written book covering the theory and practice for working with concurrency per the existing C++ standards, as well as addressing the potential changes for the upcoming C++ 20 standard. He provides a conversational discussion of the applications and best practices for concurrency along with example code to reinforce the details of each topic. An informative and worthwhile read!

Robert Badea
Technical Team Leader
Concurrency with Modern C++ is the easiest way to become an expert in the multithreading environment. This book contains both simple and advanced topics, and it has everything a developer needs, in order to become an expert in this field: Lots of content, a big number of running code examples, along with great explanation, and a whole chapter for pitfalls. I enjoyed reading it, and I highly recommend it for everyone working with C++.

Zeshuang Mi
Postgraduate
Concurrency with Modern C++ makes the multithreading's concept so clear. At the beginning of this book, it makes me know very clearly about memory model. The memory model is very important to the multithreading. The book makes me have confidence when i write my concurrent program, which makes me know what should i do or what i shouldn't do. The author elaborates the multithreading pattern which makes so helpful to me. I love it so much.
Table of Contents
-
- Reader Testimonials
-
Introduction
-
Conventions
- Special Fonts
- Special Symbols
- Special Boxes
-
Source Code
- Run the Programs
- How you should read the book?
-
Personal Notes
- Acknowledgements
- About Me
- My Special Circumstances
-
Conventions
-
A Quick Overview
-
Concurrency with Modern C++
-
C++11 and C++14: The Foundation
- Memory Model
- Multithreading
-
C++17: Parallel Algorithms of the Standard Template Library
- Execution Policy
- New Algorithms
-
The Near Future: C++20
-
std::jthread
- Atomic Smart Pointers
- Latches and Barriers
- Semaphores
- Coroutines
-
-
Case Studies
- Calculating the Sum of a Vector
- Thread-Safe Initialisation of a Singleton
- Ongoing Optimisation with CppMem
-
The Future: C++23
- Executors
- Extended futures
- Transactional Memory
- Task Blocks
- Data-Parallel Vector Library
-
Patterns and Best Practices
- Synchronisation
- Concurrent Architecture
- Best Practices
- Data Structures
- Challenges
- Time Library
- CppMem
- Glossary
-
C++11 and C++14: The Foundation
-
Concurrency with Modern C++
-
The Details
-
Memory Model
-
Basics of the Memory Model
- What is a memory location?
- What happens if two threads access the same memory location?
-
The Contract
- The Foundation
- The Challenges
-
Atomics
- Strong versus Weak Memory Model
- The Atomic Flag
-
The Class Template
std::atomic
- All Atomic Operations
- Free Atomic Functions
-
std::shared_ptr
-
The Class Template
std::atomic_ref
(C++20)
-
The Synchronisation and Ordering Constraints
- The Six Variants of Memory Orderings in C++
- Sequential Consistency
- Acquire-Release Semantic
-
std::memory_order_consume
- Relaxed Semantic
-
Fences
-
std::atomic_thread_fence
-
std::atomic_signal_fence
-
-
Basics of the Memory Model
-
Multithreading
-
Threads
- Thread Creation
- Thread Lifetime
- Thread Arguments
- Methods
-
Shared Data
- Mutexes
- Locks
- Thread-safe Initialisation
- Thread-Local Data
-
Condition Variables
- The Predicate
- Lost Wakeup and Spurious Wakeup
- The Wait Workflow
-
Tasks
- Tasks versus Threads
-
std::async
-
std::packaged_task
-
std::promise
andstd::future
-
std::shared_future
- Exceptions
- Notifications
-
Threads
-
Parallel Algorithms of the Standard Template Library
-
Execution Policies
- Parallel and Vectorised Execution
- Exceptions
- Hazards of Data Races and Deadlocks
- Algorithms
-
The New Algorithms
- More overloads
- The functional Heritage
- Performance
-
Execution Policies
-
The Near Future: C++20
-
A Cooperatively Interruptible Joining Thread
- Automatically Joining
-
Cooperatively Interruption of a
std::jthread
- Cooperative Interruption
-
Atomic Smart Pointers
- A thread-safe singly linked list
-
Coordination Types
-
std::latch
-
std::barrier
-
- Semaphores
- Synchronised Outputstreams
-
Coroutines
- A Generator Function
- Details
- The Framework
-
A Cooperatively Interruptible Joining Thread
-
Case Studies
-
Calculating the Sum of a Vector
- Single Threaded addition of a Vector
- Multithreaded Summation with a Shared Variable
- Thread-Local Summation
- Summation of a Vector: The Conclusion
-
Thread-Safe Initialisation of a Singleton
- Double-Checked Locking Pattern
- Performance Measurement
- Thread-Safe Meyers Singleton
-
std::lock_guard
-
std::call_once
withstd::once_flag
- Atomics
- Performance Numbers of the various Thread-Safe Singleton Implementations
-
Ongoing Optimisation with CppMem
- CppMem: Non-Atomic Variables
- CppMem: Locks
- CppMem: Atomics with Sequential Consistency
- CppMem: Atomics with Acquire-Release Semantic
- CppMem: Atomics with Non-atomics
- CppMem: Atomics with Relaxed Semantic
- Conclusion
- Fast Synchronisation of Threads
-
Calculating the Sum of a Vector
-
The Future: C++23
-
Executors
- A long Way
- What is an Executor?
- First Examples
- Goals of an Executor Concept
- Terminology
- Execution Functions
- A Prototype Implementation
-
Extended Futures
- Concurrency TS v1
- Unified Futures
-
Transactional Memory
- ACI(D)
- Synchronized and Atomic Blocks
-
transaction_safe
versustransaction_unsafe
Code
-
Task Blocks
- Fork and Join
-
define_task_block
versusdefine_task_block_restore_thread
- The Interface
- The Scheduler
-
Data-Parallel Vector Library
- Data-Parallel Vectors
- The Interface of the Data-Parallel Vectors
-
Executors
-
Memory Model
-
Patterns
-
Patterns and Best Practices
- History
- Invaluable Value
- Pattern versus Best Practices
- Anti-Pattern
-
Synchronisation Patterns
-
Dealing with Sharing
- Copied Value
- Thread-Specific Storage
- Future
-
Dealing with Mutation
- Scoped Locking
- Strategized Locking
- Thread-Safe Interface
- Guarded Suspension
-
Dealing with Sharing
-
Concurrent Architecture
-
Active Object
- Components
- Advantages and Disadvantages
- Implementation
- Further Information
-
Monitor Object
- Requirements
- Components
- Runtime behaviour
- Advantages and Disadvantages
- Further Information
-
Half-Sync/Half-Async
- Advantages and Disadvantages
- Reactor
- Proactor
- Further Information
-
Active Object
-
Best Practices
-
General
- Code Reviews
- Minimise Sharing of Mutable Data
- Minimise Waiting
- Prefer Immutable Data
- Use pure functions
- Look for the Right Abstraction
- Use Static Code Analysis Tools
- Use Dynamic Enforcement Tools
-
Multithreading
- Threads
- Data Sharing
- Condition Variables
- Promises and Futures
-
Memory Model
- Don’t use volatile for synchronisation
- Don’t program Lock Free
- If you program Lock-Free, use well-established patterns
- Don’t build your abstraction, use guarantees of the language
- Don’t reinvent the wheel
-
General
-
Patterns and Best Practices
-
Data Structures
-
Lock-Based Data Structures
-
General Considerations
- Locking Strategy
- Granularity of the Interface
- Typical Usage Pattern
- Avoidance of Loopholes
- Contention
- Scalability
- Invariants
- Exceptions
-
Concurrent Stack
- A Simplified Implementation
- A Complete Implementation
-
Concurrent Queue
- Coarse-Grained Locking
- Fine-Grained Locking
-
General Considerations
- Lock-Free Data Structures
-
Lock-Based Data Structures
-
Further Information
-
Challenges
- ABA Problem
- Blocking Issues
- Breaking of Program Invariants
- Data Races
- Deadlocks
- False Sharing
- Lifetime Issues of Variables
- Moving Threads
- Race Conditions
-
The Time Library
- The Interplay of Time Point, Time Duration, and Clock
-
Time Point
- From Time Point to Calendar Time
- Cross the valid Time Range
-
Time Duration
- Calculations
-
Clocks
- Accuracy and Steadiness
- Epoch
- Sleep and Wait
-
CppMem - An Overview
-
The simplified Overview
- 1. Model
- 2. Program
- 3. Display Relations
- 4. Display Layout
- 5. Model Predicates
- The Examples
-
The simplified Overview
-
Glossary
- ACID
- CAS
- Callable Unit
- Complexity
- Concurrency
- Critical Section
- Eager Evaluation
- Executor
- Function Objects
- Lambda Functions
- Lazy evaluation
- Lock-free
- Lost Wakeup
- Math Laws
- Memory Location
- Memory Model
- Modification Order
- Monad
- Non-blocking
- Parallelism
- Predicate
- Pattern
- RAII
- Release Sequence
- Sequential Consistency
- Sequence Point
- Spurious Wakeup
- Thread
- Total order
- TriviallyCopyable
- volatile
- wait-free
- Index
-
Challenges
Authors have earned$9,893,383writing, publishing and selling on Leanpub, earning 80% royalties while saving up to 25 million pounds of CO2 and up to 46,000 trees.
Learn more about writing on Leanpub
The Leanpub 45-day 100% Happiness Guarantee
Within 45 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers), EPUB (for phones and tablets) and MOBI (for Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
C++ Best Practices
Jason TurnerLevel up your C++, get the tools working for you, eliminate common problems, and move on to more exciting things!
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Functional Design and Architecture
Alexander GraninSoftware Design in Functional Programming, Design Patterns and Practices, Methodologies and Application Architectures. How to build real software in Haskell with less efforts and low risks. The first complete source of knowledge.
Atomic Kotlin
Bruce Eckel and Svetlana IsakovaFor both beginning and experienced programmers! From the author of the multi-award-winning Thinking in C++ and Thinking in Java together with a member of the Kotlin language team comes a book that breaks the concepts into small, easy-to-digest "atoms," along with exercises supported by hints and solutions directly inside IntelliJ IDEA!
C++20
Rainer GrimmC++20 is the next big C++ standard after C++11. As C++11 did it, C++20 changes the way we program modern C++. This change is, in particular, due to the big four of C++20: ranges, coroutines, concepts, and modules.
The book is almost daily updated. These incremental updates ease my interaction with the proofreaders.
Introductory Statistics with Randomization and Simulation
Mine Cetinkaya-Rundel, Christopher Barr, OpenIntro, and David DiezA complete foundation for Statistics, also serving as a foundation for Data Science, that introduces inference using randomization and simulation while covering traditional methods.
Leanpub revenue supports OpenIntro, so we can provide free desk copies to teachers interested in using our books in the classroom.
More resources: openintro.org.
Java OOP Done Right
Alan MellorObject Oriented Programming is still a great way to create clean, maintainable code. But only if you use it right.
This book gives you 25 years of OO best practice, ready to use.
You'll learn to design objects behaviour-first, use TDD to help, then confidently apply Design Patterns, SOLID principles and Refactoring to make clean, crafted code.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Composing Software
Eric ElliottAll software design is composition: the act of breaking complex problems down into smaller problems and composing those solutions. Most developers have a limited understanding of compositional techniques. It's time for that to change.
Cloud Strategy
Gregor Hohpe“Strategy is the difference between making a wish and making it come true.” A successful migration to the cloud shouldn’t be driven by wishes, but guided by a sound strategy, frameworks, and decision models. This book tells you how—without becoming superficial nor getting lost in technology and product details.
Top Bundles
- #1
Software Architecture for Developers: Volumes 1 & 2 - Technical leadership and communication
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #3
Cisco CCNA 200-301 Complet
4 Books
Ce lot comprend les quatre volumes du guide préparation à l'examen de certification Cisco CCNA 200-301. - #4
CCDE Practical Studies (All labs)
3 Books
CCDE lab - #5
Modern Management Made Easy
3 Books
Read all three Modern Management Made Easy books. Learn to manage yourself, lead and serve others, and lead the organization. - #6
The Future of Digital Health
6 Books
We put together the most popular books from The Medical Futurist to provide a clear picture about the major trends shaping the future of medicine and healthcare. Digital health technologies, artificial intelligence, the future of 20 medical specialties, big pharma, data privacy and how technology giants such as Amazon or Google want to conquer... - #7
Modern C++ by Nicolai Josuttis
2 Books
- #8
Django for Beginners/APIs/Professionals
3 Books
- #9
"The C++ Standard Library" and "Concurrency with Modern C++"
2 Books
Get my books "The C++ Standard Library" and "Concurrency with Modern C++" in a bundle. The first book gives you the details you should know about the C++ standard library; the second one dives deeper into concurrency with modern C++. In sum, you get more than 600 pages full of modern C++ and about 250 source files presenting the standard library... - #10
Linux Administration Complet
4 Books
Ce lot comprend les quatre volumes du Guide Linux Administration :Linux Administration, Volume 1, Administration fondamentale : Guide pratique de préparation aux examens de certification LPIC 1, Linux Essentials, RHCSA et LFCS. Administration fondamentale. Introduction à Linux. Le Shell. Traitement du texte. Arborescence de fichiers. Sécurité...