Performance Battle: Mutex vs CAS vs TAS vs Intel TSX
Performance Battle:
Mutex vs CAS vs TAS vs Intel TSX
std::mutex: A standard C++ lock object that provides mutual exclusion between threads.
CAS (Compare-And-Swap): An atomic operation that updates a memory location only if its current value matches an expected value.
TAS (Test-And-Set): An atomic operation that reads and sets a value simultaneously.
Intel TSX (Transactional Synchronization Extensions): An Intel technology that uses hardware transactional memory to reduce lock contention.
The following algorithm uses multiple threads to add 1 to a shared memory variable kLoop times. In this case, the sum of sum_atomic and sum_critical_section will be equal to kLoop. Although this is a highly inefficient algorithm, let's just accept it. (just for fun!)
int sum_critical_section;
std::atomic<int> sum_atomic;
void Thread() {
constexpr auto kLoop{ 2200'0000 };
constexpr auto kNumThread{ 88 };
for (int i = 0; i < kLoop / kNumThread; ++i) {
if (TryAcquire()) {
sum_critical_section += 1;
Release();
} else {
sum_atomic.fetch_add(1, std::memory_order::relaxed);
}
Idle(idle_time);
}
}An idle period was inserted between work units to control the level of contention.
(high contention: 0.6 us / low contention: 3.0 us)
TryAcquire are implemented as follows.
- Mutex
return mx.try_lock();
2. CAS
return not atomic_bool.load(std::memory_order::relaxed) and
atomic_bool.compare_exchange_strong(expected, true, std::memory_order::acquire, std::memory_order::relaxed)); // expected = false3. TAS
return not (atomic_flag.test(std::memory_order::relaxed) or atomic_flag.test_and_set(std::memory_order::acquire));4. Intel TSX
return _xbegin() == _XBEGIN_STARTED;For both CAS and TAS, the lock variable is checked before attempting the atomic operation. If the lock is already set (true), the function immediately returns false without performing the CAS or TAS operation. Otherwise, performance will degrade.
System Description
| CPU | 2 × Intel Xeon E5-2696 v4 (total 88-thread) |
|---|---|
| Build | C++23, g++ 13.3.0, -Ofast |
| OS | Ubuntu Server 24.04 |
The experiments were conducted on a two-node NUMA system. Accordingly, both sum_critical_section and sum_atomic were split into two separate counters.
Which of these four approaches do you think will win: Mutex, CAS, TAS, or Intel TSX?
Let's keep the rules simple: the winner is whichever finishes the workload the fastest.
.
.
.
.
.
.
.
.
High Contention: idle time = 0.6 us
| Algorithm | sum_critical_section | sum_atomic | elapsed seconds |
|---|---|---|---|
| Mutex | 1.04M | 21.0M | 0.521 |
| CAS | 2.06M | 19.9M | 0.333 |
| TAS | 2.00M | 20.0M | 0.335 |
| TSX | 746K | 21.2M | 0.492 |
Low Contention: idle time = 3.0 us
| Algorithm | sum_critical_section | sum_atomic | elapsed seconds |
|---|---|---|---|
| Mutex | 6.93M | 15.1M | 1.216 |
| CAS | 8.51M | 13.5M | 1.122 |
| TAS | 8.61M | 13.4M | 1.107 |
| TSX | 10.2M | 11.7M | 1.142 |
The winners of this benchmark are CAS and TAS
Of course, a benchmark win doesn't automatically make CAS or TAS superior in every situation. That said, it did win this round.
What are your thoughts on this matchup?
Errata (2026-06-08, 01:50 UTC):
Sorry!
I mentioned that, in the 2-node NUMA environment, I separated sum_critical_section and sum_atomic into two instances. However, I forgot to split the lock variables used for the mutex, CAS, and TAS implementations accordingly.
After rerunning the experiments, the winners are CAS and TAS.
=
9
u/Chuu Jun 07 '26
I've wondered if TSX is something Intel only begrudgingly supports for backwards compatibility or if they do put work into improving it. I remember when it first debuted it was promoted as a big deal and even some low end Workstation class CPUs had the feature. Now it seems regulated to server chips only and I almost never hear Intel talk about it outside of their spec sheets as supported.
4
u/kevleyski Jun 08 '26
Nice work!
3
u/DummyDDD Jun 08 '26
Tsx pretty cool. Regarding your benchmark, it is a bit surprising that tsx is faster than tas, but It's due to better behavior under contention (xbegin, xend are typically slower than xchg, but it can be faster because multiple threads can run the critical section simultaneously if they don't conflict. That tsx is faster in your benchmark only really makes sense if the contention behaves worse for xchg). It might be interesting to compare with the single threaded performance, to get an idea of how bad the contention is, and it would probably also make more sense to randomize the idle times, such that all the threads won't attempt to acquire the critical section at the same regular intervals.
You also have to remember that tsx should always be used with a fallback if the transaction fails repeatedly, as there is no guarantee that any transactions ever succeed, even if you are only using one thread, mainly because the transaction will fail on syscalls and page faults (not guaranteed, but in practice) and you generally can't know if your code will trigger a page fault.
4
u/max0x7ba https://github.com/max0x7ba Jun 09 '26
Intel TSX was discontinued in 2021 because it was susceptible to side channel timing attack that could lead to KASLR being defeated.
Support for Intel Xeon E5-2696 v4 was discontinued on June 30, 2022.
TSX is functional on your Intel Xeon E5-2696 only because you didn't install the latest BIOS update that disabled TSX.
4
u/blipman17 Jun 07 '26
std::mutex is the only one that requires the OS to cooperate as the os does the aquire and releasing of the mutex I believe. (please correct me if I'm wrong.) So this is also OS dependant if using Linux.
Realistically a good mutex implementation in a stdlib doesn't go into the kernel unless it has to yield.
There is for me the big difference, std::mutex is just the default unless it becomes a contention. So following the principle of least astonishment I'd use a Mutex.
The wakeup time or waiting to aquire time from a mutex or latch is where I'm actually the most interested in.
What happens if a thread is scheduled out since it can't continue with a blocking operation? Does the OS have a signaling mechanism for waking up that specific thread once it becomes unblocked? How efficient is that? How much latency? How does it behave in an area where threads are all used? What if multiple threads are waiting on one critical section and are genuinely asleep? (e.a. no spinlock, but scheduled out.)
But then mutex operations or non-blocking datastructures are genuinely almost never the limiting factor. The associated unseen cache invalidation that follows is the true killer of performance and can't easily be measured. And that is difficult to design around, and is also genuinely the part that I'm interested in. It also doesn't care about mutextes and atomic operations since it's all just memory to accept other data anyway.
1
u/User_Deprecated Jun 09 '26
cas/tas winning here makes sense, but the cache-line bouncing is probably the real cost.
I ended up just using per-thread queues on hot paths. no fighting over cache lines, profiles got way better.