Since C++11, the usual library has had every part a program must run work on a number of threads: std::thread to begin them, mutexes and atomics to share knowledge safely, situation variables to make threads look ahead to one another and futures at hand outcomes again. C++20 added std::jthread, latches, obstacles and semaphores. What the library can not do is make shared knowledge secure by itself, and the bugs that observe (knowledge races, deadlocks, misplaced wake-ups) are among the many hardest in C++ to search out.
This information covers every instrument with a brief, full program, and reveals how every frequent bug appears when it occurs. Each program was compiled and examined with GCC and Clang (C++17 and C++20, warnings as errors, beneath AddressSanitizer and ThreadSanitizer) and with MSVC on Home windows 11, and every output is captured verbatim.
The Quick Reply
How do you run code concurrently in C++? Begin a std::thread (or C++20 std::jthread) with a perform, and be a part of() it earlier than it goes out of scope. For a single end result, std::async returns a std::future you may wait on.
How do threads share knowledge safely? Defend shared knowledge with a std::mutex (by way of std::lock_guard or std::scoped_lock), or make it a std::atomic if it’s a single counter or flag. Two threads touching the identical knowledge with out both is a knowledge race, which is undefined conduct.
How do threads look ahead to one another? With std::condition_variable for “wait till one thing modifications”, futures for “look ahead to a end result”, and the C++20 std::latch, std::barrier and std::counting_semaphore for frequent coordination patterns.
What Is Concurrency in C++?
Concurrency means a program has a number of duties in progress on the identical time, every by itself thread of execution. On a multi-core processor the threads can run in parallel; on one core they take turns. In C++, all threads of a course of share its reminiscence, so any knowledge that multiple thread reads and writes wants synchronization.
Concurrency and parallelism are associated however totally different. Concurrency is about construction: a server that handles many consumers, a program that retains its UI responsive whereas it really works. Parallelism is about velocity: splitting one computation throughout cores. The identical instruments serve each.
The usual library’s concurrency toolkit, by header:
| Header | Essential varieties | Use it for |
|---|---|---|
<thread> |
std::thread, std::jthread (C++20), std::this_thread |
Beginning and becoming a member of threads |
<mutex> |
std::mutex, std::lock_guard, std::unique_lock, std::scoped_lock |
Defending shared knowledge |
<atomic> |
std::atomic<T> |
Lock-free counters, flags and pointers |
<condition_variable> |
std::condition_variable |
Ready till a situation turns into true |
<future> |
std::async, std::future, std::promise, std::packaged_task |
Getting outcomes and exceptions again from a thread |
<latch>, <barrier>, <semaphore> (C++20) |
std::latch, std::barrier, std::counting_semaphore |
Frequent coordination patterns |
<stop_token> (C++20) |
std::stop_token, std::stop_source |
Asking a thread to cease |
Beginning and Becoming a member of Threads
A std::thread begins working its perform as quickly as it’s constructed. Earlier than the std::thread object is destroyed, you could both be a part of() it (look ahead to it to complete) or detach() it (let it run by itself). Should you do neither, the destructor calls std::terminate and this system ends.
// threads_basics.cpp - beginning threads, passing arguments, becoming a member of, and
// std::jthread, which joins by itself.
#embrace <practical>
#embrace <iostream>
#embrace <string>
#embrace <thread>
#embrace <vector>
void fill(std::vector<int>& out, int from, int depend)
{
for (int i = 0; i < depend; ++i)
out.push_back(from + i);
}
int essential()
{
// 1. A thread runs a perform; be a part of() waits for it to complete.
std::vector<int> numbers;
std::thread employee(fill, std::ref(numbers), 10, 5); // std::ref: go by reference
employee.be a part of();
std::cout << "employee stuffed " << numbers.measurement() << " numbers, first " << numbers.entrance() << 'n';
// 2. Arguments are copied into the thread except wrapped in std::ref.
std::string label = "unchanged";
std::thread copier([](std::string s) { s += " (modified in thread)"; }, label);
copier.be a part of();
std::cout << "label after thread: " << label << 'n';
// 3. Every thread writes solely its personal slot, so no locking is required.
std::vector<lengthy> partial(4);
std::vector<std::thread> pool;
for (int t = 0; t < 4; ++t)
pool.emplace_back([&partial, t] {
for (lengthy i = t * 250; i < (t + 1) * 250; ++i)
partial[static_cast<std::size_t>(t)] += i;
});
for (std::thread& th : pool)
th.be a part of();
lengthy complete = 0;
for (lengthy p : partial)
complete += p;
std::cout << "sum of 0..999 from 4 threads: " << complete << 'n';
// 4. A std::thread that's nonetheless joinable when destroyed calls std::terminate.
// std::jthread (C++20) joins in its destructor as an alternative. See cpp20_sync.cpp.
std::cout << "{hardware} threads reported: " << (std::thread::hardware_concurrency() > 0 ? "not less than 1" : "unknown") << 'n';
}
Output:
employee stuffed 5 numbers, first 10
label after thread: unchanged
sum of 0..999 from 4 threads: 499500
{hardware} threads reported: not less than 1
Three guidelines from this program:
- Arguments are copied into the thread.
labelis unchanged as a result of the thread bought its personal copy. To go a reference, wrap the argument instd::ref, as the primary thread does withnumbers. - Threads that write totally different objects want no locking. Every of the 4 threads in step 3 writes solely
partial[t], so there is no such thing as a shared write. Gathering outcomes this manner and mixing them afterbe a part of()is the best right sample. hardware_concurrency()is a touch. It might return 0 when the quantity is unknown, so don’t divide by it.
Want be a part of() to detach(). A indifferent thread should still be working when essential returns and international objects are destroyed beneath it.
Knowledge Races: What Goes Fallacious With out Synchronization
counter.cpp has 4 threads add 1 to the identical counter 100,000 occasions every, in 3 ways:
// counter.cpp - 4 threads increment one counter 100,000 occasions every.
// counter mutex a std::mutex protects the counter (at all times 400000)
// counter atomic the counter is a std::atomic<lengthy> (at all times 400000)
// counter racy no safety: an information race, undefined conduct.
// Construct with -fsanitize=thread to see it reported.
#embrace <atomic>
#embrace <iostream>
#embrace <mutex>
#embrace <string_view>
#embrace <thread>
#embrace <vector>
constexpr int kThreads = 4;
constexpr int kIncrements = 100'000;
template <class Increment>
void run(Increment increment)
{
std::vector<std::thread> threads;
for (int t = 0; t < kThreads; ++t)
threads.emplace_back([&] {
for (int i = 0; i < kIncrements; ++i)
increment();
});
for (std::thread& t : threads)
t.be a part of();
}
int essential(int argc, char** argv)
{
const std::string_view mode = argc > 1 ? argv[1] : "mutex";
if (mode == "mutex") {
lengthy depend = 0;
std::mutex m;
run([&] {
std::lock_guard<std::mutex> lock(m); // unlocked when lock goes out of scope
++depend;
});
std::cout << "mutex: " << depend << 'n';
} else if (mode == "atomic") {
std::atomic<lengthy> depend{0};
run([&] { depend.fetch_add(1, std::memory_order_relaxed); });
std::cout << "atomic: " << depend.load() << 'n';
} else if (mode == "racy") {
lengthy depend = 0;
run([&] { ++depend; }); // two threads might learn the identical outdated worth
std::cout << "racy: " << depend << " (anticipated 400000)n";
} else racyn";
return 2;
}
The mutex and atomic variations at all times print 400,000:
mutex: 400000
atomic: 400000
The racy model is the instructive one. ++depend is three steps (learn, add, write), and two threads can learn the identical outdated worth, each add 1 and each write again the identical end result, so one increment is misplaced. Constructed with GCC at -O0, 5 runs printed:
racy: 315899 (anticipated 400000)
racy: 334104 (anticipated 400000)
racy: 312329 (anticipated 400000)
racy: 332210 (anticipated 400000)
racy: 329500 (anticipated 400000)
Clang at -O0 misplaced increments the identical method (297,661 and 323,923 in two runs). Constructed at -O2, the identical code printed 400,000 in each run with each compilers (5 with GCC, three with Clang), more than likely as a result of the optimizer turned every thread’s loop right into a single addition. That isn’t a repair. The race continues to be there; it simply didn’t present up on this compiler, at this optimization stage, on this machine. MSVC’s optimized Launch construct, then again, misplaced about 40% of the increments: 223,160, 233,193 and 235,127 in three runs. The identical supply is “right” with one compiler and badly unsuitable with one other.
This is the reason knowledge races are harmful: the C++ commonplace calls them undefined conduct, and testing alone can not show their absence. ThreadSanitizer can. Constructing with -fsanitize=thread (GCC and Clang) finds the race on the primary run, at any optimization stage:
WARNING: ThreadSanitizer: knowledge race (pid=300)
#0 operator() src/counter.cpp:47
SUMMARY: ThreadSanitizer: knowledge race src/counter.cpp:47 in operator()
Line 47 is the ++depend within the racy lambda. The mutex and atomic variations run clear beneath ThreadSanitizer, and so does each different program on this information. Run your exams beneath it often; it’s the single most great tool for concurrent C++.
Mutexes, Locks and Atomics
A std::mutex lets one thread at a time right into a important part. By no means name lock() and unlock() your self: if the code in between throws or returns early, the mutex stays locked endlessly. Use a lock object that unlocks in its destructor, the identical RAII concept described in C++ reminiscence administration:
| Lock | Locks | Use it when |
|---|---|---|
std::lock_guard<std::mutex> |
One mutex, for the entire scope | The default for a easy important part |
std::scoped_lock (C++17) |
A number of mutexes without delay, deadlock-free | You want two or extra mutexes |
std::unique_lock<std::mutex> |
One mutex; can unlock early, relock, be moved | With situation variables, or to unlock earlier than gradual work |
A std::atomic<T> makes single operations on one variable indivisible with no lock. depend.fetch_add(1) is secure from any variety of threads. Atomics are the correct instrument for counters, flags and “has this occurred but” states; something that spans two variables (a steadiness and a transaction log, say) nonetheless wants a mutex, as a result of two separate atomic operations will not be atomic collectively.
The std::memory_order_relaxed argument in counter.cpp says the increment doesn’t have to order another reminiscence operations, which is true for a pure counter that’s learn after be a part of(). The default, std::memory_order_seq_cst, is at all times right and the correct selection except you’ve measured a cause to weaken it.
Avoiding Impasse with std::scoped_lock
A impasse occurs when two threads every maintain one mutex and look ahead to the opposite’s. The basic case is a switch between two accounts, run in reverse instructions:
// transfers.cpp - shifting cash between two accounts from two threads in
// reverse instructions. Locking each mutexes with std::scoped_lock avoids the
// impasse that locking them separately, in numerous orders, may cause.
#embrace <iostream>
#embrace <mutex>
#embrace <thread>
struct Account {
std::mutex m;
lengthy steadiness = 0;
};
void switch(Account& from, Account& to, lengthy quantity)
{
std::scoped_lock lock(from.m, to.m); // locks each, deadlock-free, in any order
from.steadiness -= quantity;
to.steadiness += quantity;
}
int essential()
{
Account a, b;
a.steadiness = 1000;
b.steadiness = 1000;
std::thread t1([&] { for (int i = 0; i < 100'000; ++i) switch(a, b, 1); });
std::thread t2([&] { for (int i = 0; i < 100'000; ++i) switch(b, a, 1); });
t1.be a part of();
t2.be a part of();
std::cout << "a = " << a.steadiness << ", b = " << b.steadiness
<< ", complete = " << a.steadiness + b.steadiness << 'n';
}
Output:
a = 1000, b = 1000, complete = 2000
std::scoped_lock lock(from.m, to.m) locks each mutexes utilizing a deadlock-avoidance algorithm, so the order of the arguments doesn’t matter. Changing it with two std::lock_guards, from.m first and to.m second, deadlocked in every of three take a look at runs: thread 1 locked a and waited for b whereas thread 2 locked b and waited for a, and this system needed to be killed after 10 seconds. The take a look at suite’s deliberate-mistake verify makes precisely that change and confirms the take a look at catches the hold.
The final rule: if code ever holds two locks, both take them along with std::scoped_lock or at all times take them in a single international order.
Situation Variables: A Thread-Protected Bounded Queue
A producer-consumer queue is the workhorse of concurrent applications: some threads put work in, others take it out, and a capability restrict stops producers from working far forward. It wants a mutex for the info and two situation variables, one for “not full” and one for “not empty”:
// bounded_queue.h - a thread-safe queue with a capability restrict.
// push() waits whereas the queue is full; pop() waits whereas it's empty.
// shut() wakes everybody: pop() then drains what's left and returns
// std::nullopt, and push() returns false.
#pragma as soon as
#embrace <condition_variable>
#embrace <cstddef>
#embrace <deque>
#embrace <mutex>
#embrace <optionally available>
#embrace <utility>
template <class T>
class BoundedQueue {
public:
express BoundedQueue(std::size_t capability) : capacity_(capability) {}
bool push(T worth)
{
std::unique_lock<std::mutex> lock(mutex_);
// wait() unlocks, sleeps and relocks; the predicate guards in opposition to
// spurious wakeups and in opposition to situations that modified earlier than we woke.
not_full_.wait(lock, [this] );
if (closed_)
return false;
items_.push_back(std::transfer(worth));
lock.unlock(); // notify after unlocking: the woken thread can run without delay
not_empty_.notify_one();
return true;
}
std::optionally available<T> pop()
{
std::unique_lock<std::mutex> lock(mutex_);
not_empty_.wait(lock, [this] closed_; );
if (items_.empty())
return std::nullopt; // closed and drained
T worth = std::transfer(items_.entrance());
items_.pop_front();
lock.unlock();
not_full_.notify_one();
return worth;
}
void shut()
{
{
std::lock_guard<std::mutex> lock(mutex_);
closed_ = true;
}
not_empty_.notify_all();
not_full_.notify_all();
}
non-public:
std::mutex mutex_;
std::condition_variable not_full_;
std::condition_variable not_empty_;
std::deque<T> items_;
const std::size_t capacity_;
bool closed_ = false;
};
Three particulars make it right:
- All the time wait with a predicate.
wait(lock, [] { return ...; })re-checks the situation after each wake-up. With out it, a spurious wakeup (which the usual permits) or a situation that modified earlier than the thread bought the lock would letpop()learn from an empty queue. shut()should wake everybody. Shoppers blocked inpop()sleep till notified. Ifshut()set the flag with outnotify_all(), they’d sleep endlessly. The deliberate-mistake verify removes that decision, and the take a look at hangs till its timeout.- Notify after unlocking. Calling
notify_one()afterlock.unlock()lets the woken thread take the mutex without delay as an alternative of waking up solely to dam on it.
Two producers ship +1 to +10,000 and -1 to -10,000; three customers add up what they obtain:
// producer_consumer.cpp - two producers and three customers share a
// BoundedQueue with room for 8 objects.
#embrace "bounded_queue.h"
#embrace <iostream>
#embrace <thread>
#embrace <vector>
int essential()
{
BoundedQueue<int> queue(8);
constexpr int kPerProducer = 10'000;
std::vector<std::thread> producers;
for (int p = 0; p < 2; ++p)
producers.emplace_back([&queue, p] {
for (int i = 1; i <= kPerProducer; ++i)
queue.push(p == 0 ? i : -i); // producer 1 sends negatives
});
// Every client provides up what it receives in its personal variables.
std::vector<lengthy> sums(3), counts(3);
std::vector<std::thread> customers;
for (std::size_t c = 0; c < 3; ++c)
customers.emplace_back([&, c] {
whereas (auto merchandise = queue.pop()) {
sums[c] += *merchandise;
++counts[c];
}
});
for (std::thread& t : producers)
t.be a part of();
queue.shut(); // no extra objects: let customers end
for (std::thread& t : customers)
t.be a part of();
lengthy complete = 0, acquired = 0;
for (std::size_t c = 0; c < 3; ++c) {
complete += sums[c];
acquired += counts[c];
}
std::cout << "objects acquired: " << acquired << 'n'
<< "sum (ought to be 0): " << complete << 'n'
<< "push after shut accepted: " << std::boolalpha << queue.push(1) << 'n';
}
Output:
objects acquired: 20000
sum (ought to be 0): 0
push after shut accepted: false
All 20,000 objects arrive, the sum is strictly zero and no merchandise is misplaced or duplicated, whichever client occurred to take every one.
Futures: Outcomes and Exceptions from Different Threads
When a thread exists to compute one worth, a future is easier than a shared variable and a mutex:
// futures.cpp - getting outcomes and exceptions again from different threads:
// std::async, std::promise and std::packaged_task.
#embrace <cstddef>
#embrace <future>
#embrace <iostream>
#embrace <numeric>
#embrace <stdexcept>
#embrace <thread>
#embrace <vector>
lengthy sum_range(const std::vector<int>& v, std::size_t from, std::size_t to)
{
return std::accumulate(v.start() + static_cast<std::ptrdiff_t>(from), v.start() + static_cast<std::ptrdiff_t>(to), 0L);
}
int parse_positive(int worth)
{
if (worth <= 0)
throw std::invalid_argument("worth have to be optimistic");
return worth;
}
int essential()
{
std::vector<int> knowledge(1000);
std::iota(knowledge.start(), knowledge.finish(), 1); // 1..1000
// std::async: run a perform and get its end result by way of a future.
// std::launch::async forces a brand new thread as an alternative of presumably deferring.
auto first_half = std::async(std::launch::async, sum_range, std::cref(knowledge), std::size_t{0}, std::size_t{500});
const lengthy second_half = sum_range(knowledge, 500, 1000);
std::cout << "async sum: " << first_half.get() + second_half << 'n';
// An exception thrown within the activity is saved and rethrown by get().
auto unhealthy = std::async(std::launch::async, parse_positive, -5);
strive {
unhealthy.get();
} catch (const std::invalid_argument& e) {
std::cout << "exception from the opposite thread: " << e.what() << 'n';
}
// std::promise: a thread units the worth at any time when it's prepared.
std::promise<std::string> promise;
std::future<std::string> greeting = promise.get_future();
std::thread sender([p = std::move(promise)]() mutable { p.set_value("good day from a promise"); });
std::cout << greeting.get() << 'n';
sender.be a part of();
// std::packaged_task: wrap a callable now, run it afterward any thread.
std::packaged_task<int(int)> activity(parse_positive);
std::future<int> end result = activity.get_future();
std::thread runner(std::transfer(activity), 42);
std::cout << "packaged_task end result: " << end result.get() << 'n';
runner.be a part of();
}
Output:
async sum: 500500
exception from the opposite thread: worth have to be optimistic
good day from a promise
packaged_task end result: 42
std::asyncruns a perform and returns astd::futurefor its end result. Crossstd::launch::asyncto ensure a brand new thread; with out it, the implementation might defer the decision tillget(), working it on the calling thread.- Exceptions journey by way of the long run.
parse_positive(-5)throws on the opposite thread;get()rethrows it on this one. That is the principle benefit over a uncookedstd::thread, the place an uncaught exception terminates this system. The exception dealing with information covers what to do with it. std::promiseseparates producing a price from the perform name: any thread canset_value()(orset_exception()) at any time when the result’s prepared.std::packaged_taskwraps a callable so you may run it later, on any thread, and nonetheless get a future.
One entice: the destructor of a future returned by std::async waits for the duty to complete. Calling std::async with out retaining the end result subsequently runs the duty synchronously, and two such calls in a row run one after the opposite.
C++20: jthread, Cease Tokens, Latches, Boundaries and Semaphores
C++20 added 5 instruments that substitute frequent hand-written patterns:
// cpp20_sync.cpp - the C++20 additions: std::jthread with a cease token,
// std::latch, std::barrier and std::counting_semaphore.
#embrace <algorithm>
#embrace <atomic>
#embrace <barrier>
#embrace <chrono>
#embrace <iostream>
#embrace <latch>
#embrace <semaphore>
#embrace <thread>
#embrace <vector>
int essential()
{
// 1. jthread: request_stop() asks the thread to complete; the destructor joins.
std::atomic<int> ticks{0};
{
std::jthread ticker([&ticks](std::stop_token cease) {
whereas (!cease.stop_requested()) {
++ticks;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
whereas (ticks < 5)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
ticker.request_stop();
} // joined right here, no express be a part of() wanted
std::cout << "jthread stopped after not less than 5 ticks: " << std::boolalpha << (ticks >= 5) << 'n';
// 2. latch: a one-shot countdown. essential waits till all 3 employees are prepared.
std::latch prepared(3);
std::vector<std::jthread> employees;
for (int i = 0; i < 3; ++i)
employees.emplace_back([&ready] { prepared.count_down(); });
prepared.wait();
std::cout << "latch: all 3 employees readyn";
employees.clear(); // jthreads be a part of as they're destroyed
// 3. barrier: threads meet on the finish of every part; the completion
// perform runs as soon as per part, earlier than anybody continues.
int phases_done = 0;
std::barrier sync(3, [&phases_done]() noexcept { ++phases_done; });
for (int i = 0; i < 3; ++i)
employees.emplace_back([&sync] {
for (int part = 0; part < 4; ++part)
sync.arrive_and_wait();
});
employees.clear();
std::cout << "barrier: " << phases_done << " phases completedn";
// 4. counting_semaphore: at most 2 of the 6 threads inside without delay.
std::counting_semaphore<2> slots(2);
std::atomic<int> inside{0}, most{0};
for (int i = 0; i < 6; ++i)
employees.emplace_back([&] {
slots.purchase();
const int now = ++inside;
int seen = most.load();
whereas (now > seen && !most.compare_exchange_weak(seen, now)) {
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
--inside;
slots.launch();
});
employees.clear();
std::cout << "semaphore: at most " << most.load() << " threads inside at oncen";
}
Output:
jthread stopped after not less than 5 ticks: true
latch: all 3 employees prepared
barrier: 4 phases accomplished
semaphore: at most 2 threads inside without delay
| Device | Use as an alternative of | Habits |
|---|---|---|
std::jthread |
std::thread plus a guide be a part of() |
Joins in its destructor, and passes a std::stop_token to its perform |
std::stop_token |
A hand-rolled std::atomic<bool> “please cease” flag |
request_stop() units it; the thread checks stop_requested() |
std::latch |
A counter plus a situation variable | Counts down as soon as; wait() returns when it reaches zero |
std::barrier |
Repeated latches | Reusable: threads meet on the finish of every part, and an optionally available perform runs as soon as per part |
std::counting_semaphore |
A mutex-protected counter of free slots | purchase() takes a slot, launch() returns it; limits what number of threads do one thing without delay |
std::jthread is the one to undertake first: it removes the “forgot to affix” crash, and cease tokens make cancellation express as an alternative of an advert hoc flag. In this system above, six threads compete for a two-slot semaphore and at most two are ever inside, because the output confirms.
Frequent Errors in Concurrent C++
- Sharing a variable with no mutex or an atomic. Even
++dependis an information race. Run the exams beneath ThreadSanitizer. - Trusting a passing take a look at. The racy counter printed the correct reply each time with GCC and Clang at
-O2, and misplaced 40% of its updates with MSVC. A race can keep hidden for a very long time. - Calling
lock()andunlock()by hand. An exception between them leaves the mutex locked. Usestd::lock_guardorstd::scoped_lock. - Taking two locks in numerous orders. Use
std::scoped_lockfor each, or a set order. - Ready on a situation variable with no predicate. Spurious wakeups and missed notifications break it.
- Forgetting to inform waiters on shutdown. Threads blocked in
wait()by no means see the closed flag. - Destroying a joinable
std::thread. This system terminates. Be a part of it, or usestd::jthread. - Holding a lock whereas doing gradual work (I/O, allocation, calling consumer code). Copy what you want, unlock, then work.
- Assuming
std::asyncwith outstd::launch::asyncruns in parallel. It might be deferred. - Capturing native variables by reference in a indifferent thread. The perform returns, the locals die and the thread reads freed reminiscence.
Key Takeaways
- Begin threads with
std::threadorstd::jthread; be a part of eachstd::threadearlier than it’s destroyed. - Any knowledge that one thread writes and one other reads wants a mutex or an atomic. With out one it’s a knowledge race and undefined conduct.
- Use RAII locks:
std::lock_guardfor one mutex,std::scoped_lockfor a number of. - Wait on situation variables with a predicate, and notify waiters once you shut down.
- Use futures to get outcomes and exceptions again from different threads.
- In C++20, favor
std::jthreadwith cease tokens, and use latches, obstacles and semaphores as an alternative of hand-written equivalents. - Take a look at concurrent code beneath ThreadSanitizer: it finds races that odd exams miss.
Conclusion
Concurrent C++ comes down to 2 questions for each piece of knowledge: which threads contact it, and what stops them from touching it on the identical time. The usual library solutions the second with a small set of instruments: mutexes and atomics for sharing, situation variables and futures for ready and the C++20 primitives for the frequent patterns constructed on prime of them. The bugs come from the primary query, and the instruments that discover them, ThreadSanitizer above all, are as a lot part of writing concurrent code because the threads themselves.
For an actual program constructed on these items, the named pipes article makes use of one std::thread per consumer, and sensible pointers in C++ explains which shared_ptr operations are thread-safe. Extra C++ matters are within the C++ part.
Supply Code and Assessments
All applications on this web page are within the fundamentals/concurrency listing of the MYCPLUS C++ examples repository.
Construct and take a look at:
cmake -S . -B construct
cmake --build construct --config Launch
ctest --test-dir construct -C Launch --output-on-failure
What the construct checks.
- Compilers: GCC and Clang beneath C++17 and C++20 with
-Wall -Wextra -pedantic -Werror, and MSVC with/W4 /WX /permissive-.cpp20_sync.cppis at all times constructed as C++20. - Output: every program prints precisely the output proven on this web page. Each take a look at has a timeout, as a result of a concurrency bug usually reveals up as a hold somewhat than a unsuitable reply.
- Sanitizers: on Linux, each take a look at additionally runs beneath AddressSanitizer with UndefinedBehaviorSanitizer and beneath ThreadSanitizer, and ThreadSanitizer should report the race in
counter racy. - Repetition: the workflow runs the suite 5 occasions in a row, to catch exams that go solely by luck.
What I Verified
All the things within the Ubuntu column was run for this text on Ubuntu 24.04 (x86-64, 2 cores, GCC 13.3, Clang 18.1, CMake 3.28). The Home windows column comes from run_all.ps1 within the repository, run on Home windows 11 (construct 26300) with MSVC.
| Examine | Ubuntu 24.04 | Home windows 11 |
|---|---|---|
| Construct with warnings as errors | GCC and Clang, C++17 and C++20: handed | MSVC /W4 /WX /permissive-, C++17 and C++20: handed |
| CTest: 7 output comparisons | 7 of seven in all 4 configurations | 7 of seven in C++17 and in C++20 |
| Each take a look at 20 occasions in a row | 20 of 20 (GCC, C++17) | 20 of 20 (MSVC, C++17) |
| AddressSanitizer and UndefinedBehaviorSanitizer, each take a look at | 7 of seven, clear | Not relevant |
| ThreadSanitizer, each take a look at | 7 of seven, clear; the racy counter reported | Not relevant |
| Valgrind memcheck, each program | No errors, no leaks | Not relevant |
| Deliberate errors {that a} take a look at should catch | All 4 caught | All 3 caught (the removed-lock mistake wants ThreadSanitizer) |
Not lined: parallel algorithms (std::execution::par), coroutines, lock-free knowledge constructions past a single atomic and reminiscence orders apart from relaxed and sequentially constant.

