Mutex and Atomics
Protecting a shared sum in C++ with std::mutex, a lock held over the whole loop, and std::atomic, and what each one costs.

Protecting a value with a simple mutex:
#include <iostream>
#include <thread>
#include <mutex>
long long sum{0};
std::mutex m_tex{};
void calcSum(int start, int end){
for(int x=start; x <= end; x++ ){
m_tex.lock();
sum += x;
m_tex.unlock();
}
}
int main()
{
calcSum(0, 10000000);
std::cout << "Normal Calculation " << sum << std::endl;
sum = 0;
std::thread t1(calcSum, 0, 5000000);
std::thread t2(calcSum, 5000001, 10000000);
t1.join();
t2.join();
std::cout << "Thread Calculation " << sum << std::endl;
}
I use long long for the sum. The result is about 5 * 10^13, which doesn’t fit in a 32-bit long (on Windows long is 32 bits even on 64-bit systems).
Locking and unlocking for every single addition is expensive, so with two threads fighting over the same mutex this version can easily be slower than the single-threaded one.
The other way is using unique_lock, but here it locks the whole loop, so the threads can’t really run in parallel. One thread does all of its work while the other waits.
#include <iostream>
#include <thread>
#include <mutex>
long long sum{0};
std::mutex m_tex{};
void calcSum(int start, int end){
std::unique_lock<std::mutex> unilock(m_tex);
for(int x=start; x <= end; x++ ){
sum += x;
}
}
int main()
{
calcSum(0, 10000000);
std::cout << "Normal Calculation " << sum << std::endl;
sum = 0;
std::thread t1(calcSum, 0, 5000000);
std::thread t2(calcSum, 5000001, 10000000);
t1.join();
t2.join();
std::cout << "Thread Calculation " << sum << std::endl;
}
unique_lock unlocks the mutex in its destructor, so it is also exception safe. If you don’t need to unlock early or move the lock around, std::lock_guard is enough. And if you ever need to lock more than one mutex at the same time, use std::scoped_lock (C++17), e.g. std::scoped_lock lock(m1, m2);. It locks all of them with a deadlock avoidance algorithm.
A better design for this example is to let each thread sum into a local variable and lock only once at the end to add its partial result to sum. Then the threads really work in parallel.
New memory model: atomic
std::atomic gives us a safe way to share data in memory without a mutex. Each sum += x is a single atomic read-modify-write, so there is no data race. For a simple counter like this it is usually faster than locking a mutex on every step, but it is still much slower than a plain variable, because the cores have to keep fighting over the same cache line.
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<long long> sum{0};
void calcSum(int start, int end){
for(int x=start; x <= end; x++ ){
sum += x;
}
}
int main()
{
calcSum(0, 10000000);
std::cout << "Normal Calculation " << sum.load() << std::endl;
sum = 0;
std::thread t1(calcSum, 0, 5000000);
std::thread t2(calcSum, 5000001, 10000000);
t1.join();
t2.join();
std::cout << "Thread Calculation " << sum.load() << std::endl;
}
By default all atomic operations use std::memory_order_seq_cst, the strongest ordering. For a pure counter where nothing else depends on the order, sum.fetch_add(x, std::memory_order_relaxed) is enough, and join makes the final value visible to the main thread. Only use relaxed ordering when you are sure no other data is published through that variable.