Book Image

Concurrency with Modern C++

By : Rainer Grimm
Book Image

Concurrency with Modern C++

By: Rainer Grimm

Overview of this book

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20/23. Concurrency with Modern C++ is a practical guide that gets you to grips with concurrent programming in Modern C++. Starting with the C++ memory model and using many ready-to-run code examples, the book covers everything you need to improve your C++ multithreading skills. You'll gain insight into different design patterns. You'll also uncover the general consideration you have to keep in mind while designing a concurrent data structure. The final chapter in the book talks extensively about the common pitfalls of concurrent programming and ways to overcome these hurdles. By the end of the book, you'll have the skills to build your own concurrent programs and enhance your knowledge base.
Table of Contents (19 chapters)
Free Chapter
1
Reader Testimonials
19
Index

Breaking of Program Invariants

Program invariants are invariants that should hold for the entire lifetime of your program.

Malicious race condition breaks an invariant of the program. The invariant of the program is that the sum of all balances should be the same amount. Which in our case is 200 euros because each account starts with 100 euro (line 9). I neither want to create money by transferring it nor do I want to destroy it.

Breaking an invariant of the program
 1 // breakingInvariant.cpp
 2 
 3 #include <atomic>
 4 #include <functional>
 5 #include <iostream>
 6 #include <thread>
 7 
 8 struct Account{
 9   std::atomic<int> balance{100};                               
10 };
11                                                             
12 void transferMoney(int amount, Account& from, Account& to){
13   using namespace std::chrono_literals;
14   if (from.balance >= amount){
15     from.balance -= amount;  
16     std::this_thread:...