Skip to content

Repository files navigation

FastSpinLock

FastSpinLock is a minimal, header‑only C++ spinlock implemented using a single std::atomic<bool> and a test‑and‑set acquire loop. It is designed for cases where extremely low uncontended latency is required and where the user understands the tradeoffs of a pure TAS spinlock under contention.

FastSpinLock has:

  • zero dependencies
  • zero kernel involvement
  • no futex fallback
  • no fairness guarantees
  • a fast uncontended path
  • predictable behavior for micro‑critical sections
  • a BSD 2-clause license

This project includes:

  • the header‑only lock implementation (FastSpinLock.hpp)
  • a benchmark directory (benchmark/), that compares FastSpinLock against std::mutex from 0-29 worker threads (1-30 total threads including main). Gnuplot scripts (and png files) associated with a run on a CentOS 7 40-core 3.1 GHZ single-socket CPU and their input CSV files and output PNG files are attached in the repo. bench64\ and bench128\ are identical to benchmark\, except that they are modified to use alignas(64) and alignas(128), respectively.
  • Unit tests (tests/) covering std::lock_guard, std::unique_lock, std::conditional_variable_any, and try_lock(). Optional CMake flags (mutually exclusive): -DCOVERAGE=ON (gcov/lcov report via coverage target), -DASAN=ON (AddressSanitizer via asan target), -DTSAN=ON (ThreadSanitizer via tsan target), -DUBSAN=ON (UndefinedBehaviorSanitizer via ubsan target).

Quick Start

#include "FastSpinLock.hpp"

FastSpinLock mtx;

void example() {
    std::lock_guard<FastSpinLock> lock(mtx);
    // critical section
}

Design Rationale

std::mutex is implemented (on Linux) on top of futex(). It's good, it's stable, it's not particularly performant. I've ended up writing high performance replacements at three different companies, from scratch (because they were done on company resources and time). For lower thread-count, a much more efficient solution exists, since we don't have to worry about "contention forever" cases. This is an open source equivalent that takes into consideration my multi-core, NUMA aware work, up to 4096 cores over decades of programming.

This code is actually the completion of the code that I wrote on my own time, that I made available to those three companies. This code adds try_lock, unit tests, and formalizes the benchmarks, over what was copied and used at those companies.

The idea is, that well designed code should have mutexes around small numbers of threads, with them being held for limited amounts of time. This implementation is optimized for that case. std::mutex is implemented for the generic "do no harm" case.

Compatibility

This class is a direct drop in for std::mutex, with one exception - std::condition_variable is not compatible. If you want to use this, use std::condition_variable_any instead.

Where it should be used instead of std::mutex

This class is designed to have the least overhead possible with the basic rule that locks should be held for very short periods of time, and a thread should never get descheduled in a lock state (such as doing a message to the systemd-journald logs, or to disk files).

This is designed for typical use cases where there are a relatively small number of threads that share a mutex. For example, an MPMC queue with 16 or fewer threads that can own the lock get better performance than std::mutex, at significantly lower CPU time (user+system). At 18-threads, that flips.

If more threads exist than cores, std::mutex will probably be the way to go, because this doesn't deschedule to prevent CPU thrashing.

It also doesn't protect against lock(A) ; lock(B) in one thread, and lock(B) and lock(A) in another. I don't believe std::mutex protects against this case either.

Performance summary

Threads FastSpinLock std::mutex
1-9 Faster Slower
10-17 Comparable Comparable
18+ Slower Faster
Pass 10 (mylock)

Header‑Only Lock

class FastSpinLock {
public:
    FastSpinLock() {
        m_lock = false;
    }

    FastSpinLock(const FastSpinLock&) = delete;
    FastSpinLock& operator=(const FastSpinLock&) = delete;

    void lock() {
        while (std::atomic_exchange_explicit(&m_lock, true,
                                             std::memory_order_acquire))
            ;
    }
    void unlock() {
        std::atomic_store_explicit(&m_lock, false,
                                   std::memory_order_release);
    }
    bool try_lock() {
        return !std::atomic_exchange_explicit(&m_lock, true, std::memory_order_acquire);
    }
private:
    std::atomic<bool> m_lock;
};

When to Use

FastSpinLock is appropriate when:

  • the critical section is only a few instructions;
  • the contention is expected to be low;
  • the lock is used in tight loops when std::mutex overhead dominates;
  • you want predictable, minimal overhead in the uncontended case.

When Not to Use

FastSpinLock should not be used when:

  • contention is high;
  • fairness is required;
  • threads may block for long periods;
  • the critical section performs I/O or system calls;
  • you need priority inheritance or wakeup ordering guarantees

Under contention, a TAS spinlock will generate cacheline ping-pong and degrade rapidly (which you will see for the larger core counts in the graphs). This is expected and inherent to the design.

Notes, from experience

If you have lots of threads and each locks the same mutex, you should consider fixing your design.

Example 1

If you use std::lock_guard and do logs or system calls within the lock state, you should consider your code, and narrow the scope of the locks (with a more limited open/close bracing protection of the lock).

{
    std::lock_guard(std::mutex) lock;
    // access protected data
    // then write data to disk
}

Is better represented by

{
    std::vector<uint8_t> copy;
    {
        std::lock_guard(std::mutex) lock;
        // access protected data
        // copy protected data to "copy"
    }
    // then write data to disk
}

This is an example of how to reduce lock state with std::mutex. FastSpinLock would get the same benefit.

Example 2

I once worked at a company that did geolocation of cellular data at the eNodeB (LTE) layer - each eNodeB had one thread, so in typical use cases, a server supported about 800 eNodeB's, so we had 800 threads with data. Each thread pushed to a single queue the data it read from cell phones. The queue had a mutex. On a 32-core server, you had about a 1/32 chance of getting a lock (about 3%) to push to the queue. It worked OK, but was slow. When we deployed on a 96 core server, you had a 1/96 chance of getting the lock (about 1%). Performance was less than acceptable. Crappy design. The queue simply aggregated data from the sources.

We were actually able to get this to be lock-free - we used TLS. Each thread appended to a buffer, when the buffer filled, we output to a socket (which was what the old queue did on the receiving side - one buffer, not one buffer per eNodeB). This change gave screaming good performance.

So the key here, if you can get rid of a mutex via smart programming, do that before switching to FastSpinLock (note, FastSpinLock would not have worked here (we tried something similar) because of the huge number of threads doing locks).

Benchmark results

This first plot compares locks/second for FastSpinLock and std::mutex. The FastSpinLock values correspond to FastSpinLock in the graphs. std::mutex labels correspond to the std::mutex values in the graphs.

The tests run with main always doing lock/unlock, and a number of threads from 0 through 29. The X axis is the number of threads, so the values at 0 actually have a main process and zero threads doing locks/unlocks, and the value at 29 has main and 29 other threads doing locks and unlocks.

Each test does 10 tests each for each of FastSpinLock and std::mutex at each number of threads.

In this plot, the larger numbers along the Y axis are best.

locks per second

And the second takes the cumulative CPU time of the threads (including the clock_gettime() calls around the lock/unlock calls and the loop overhead).

In this plot, the smaller numbers on the Y axis are best. Note that the degradation of std::mutex is linear, and, when FastSpinLock flips from better to worse (18 total threads), it fails catastrophically.

user + system CPU time

Benchmarking with alignas(64) and alignas(128)

The same benchmark plotted in the two plots was run with both Mutex classes being set as alignas(64) and alignas(128), since both are valid cache line sizes. Like above, the test ran 10 iterations for each of FastSpinLock and std::mutex, for 0 through 29 threads (plus the main program). The following table shows the results for no-align, 64-bit align, and 128-bit align, for lock rate and sum(user+system) averaged.

We also measured the effect of alignas(64) and alignas(128). The results showed a consistent performance cost on the uncontended and lightly-contended paths that matter most for this lock, so the shipped version remains unaligned. Full numbers are available in alignment-results.md.

For the percent values, +/- 5% is left in black. If it's worse outside that range, it's in red.

If it's better outside that range, it's in green.

Notice that for Locks/second, the optimal point in the data is at 7 threads (main + 7 threads), where we see 3.6 times the number of locks/second than we do with std::mutex. And for user+system time (CPU time) we see 38.6% of the CPU time for FastSpinLock in this case over std::mutex. Another thing to note, that for FastSpinLock, there is near-zero (zero for when we FastSpinLock is better than std::mutex) System time, whereas with std::mutex, most of the time is system time, so, FastSpinLock has zero context switch overhead (which doesn't show up in a program's CPU time numbers). Note that the color of alignas(64) User+System time has a bug - it shows up as black, not red, for 19+ cores (and main). This will be fixed in a future commit.

A More detailed table that includes the alignas can be found at this link.

Threads std::mutex FastSpinLock
Locks/Second User+System Time Locks/Second User+System Time
Locks/Second As a Percent
(Greater Than 100% is best)
User+System Time As a Percent
(Less Than 100% is best)
Locks/Second As a Percent
(Greater Than 100% is best)
User+System Time As a Percent
(Less Than 100% is best)
Percent Percent Percent
0 35414052.507 4.396 50239938.956 3.569
pct 141.864 🟒 81.187 🟒
1 6990012.858 37.619 11759434.207 26.474
pct 168.232 🟒 70.374 🟒
2 3272492.196 102.538 7502863.296 59.608
pct 229.271 🟒 58.133 🟒
3 1885010.299 225.943 5164591.796 113.780
pct 273.982 🟒 50.358 🟒
4 1417964.998 366.041 4458619.622 158.810
pct 314.438 🟒 43.386 🟒
5 1138799.643 537.703 3939322.394 211.964
pct 345.919 🟒 39.420 🟒
6 945769.780 746.572 3325069.884 290.690
pct 351.573 🟒 38.937 🟒
7 836535.678 961.314 3013608.954 370.999
pct 360.249 🟒 38.593 🟒
8 775009.779 1166.861 2625843.613 480.796
pct 338.814 🟒 41.204 🟒
9 723996.882 1388.784 2372237.816 595.976
pct 327.659 🟒 42.914 🟒
10 656427.583 1670.827 1690339.496 810.949
pct 257.506 🟒 48.536 🟒
11 603668.719 1981.581 1569975.837 957.713
pct 260.072 🟒 48.331 🟒
12 536487.284 2412.810 1369233.273 1181.085
pct 255.222 🟒 48.951 🟒
13 496325.478 2809.605 1193316.741 1432.677
pct 240.430 🟒 50.992 🟒
14 467443.119 3206.408 1041810.636 1748.546
pct 222.874 🟒 54.533 🟒
15 440130.536 3633.573 970833.216 2009.033
pct 220.578 🟒 55.291 🟒
16 414139.710 4100.720 861772.777 2392.358
pct 208.087 🟒 58.340 🟒
17 392847.916 4579.473 752392.072 2869.932
pct 191.522 🟒 62.669 🟒
18 365887.530 5172.732 399494.439 5530.730
pct 109.185 🟒 106.921 πŸ”΄
19 343351.266 5812.136 243713.205 8515.741
pct 70.981 πŸ”΄ 146.517 πŸ”΄
20 324448.738 6450.764 178067.169 12022.858
pct 54.883 πŸ”΄ 186.379 πŸ”΄
21 312572.668 7011.467 152096.561 14738.142
pct 48.660 πŸ”΄ 210.201 πŸ”΄
22 302066.350 7586.841 158692.741 14793.030
pct 52.536 πŸ”΄ 194.983 πŸ”΄
23 286355.688 8347.043 115680.672 21079.547
pct 40.398 πŸ”΄ 252.539 πŸ”΄
24 276649.441 9002.962 126209.119 20201.617
pct 45.621 πŸ”΄ 224.389 πŸ”΄
25 266688.795 9719.040 98653.874 26817.789
pct 36.992 πŸ”΄ 275.930 πŸ”΄
26 256041.460 10489.049 107740.816 25221.200
pct 42.079 πŸ”΄ 240.453 πŸ”΄
27 241578.440 11533.465 83281.079 33711.036
pct 34.474 πŸ”΄ 292.289 πŸ”΄
28 231696.014 12452.959 92065.063 31689.874
pct 39.735 πŸ”΄ 254.477 πŸ”΄
29 223745.574 13342.744 73367.133 41130.458
pct 32.790 πŸ”΄ 308.261 πŸ”΄

Build and Run Benchmarks

cd benchmark
bash run2.sh
gnuplot results.gp
eog *.png

Alignment benchmarks

The alignment (alignas) tests are done in two directories that are modified from benchmark - bench64 and bench128.

To run the benchmarks there, do the same procedure as above, simply replacing the directory name.

The alignment table above is built by running the 3 benchmarks, and then running

bash combineResults.sh

and then taking the output of readmeHtml.txt and putting it inside the tbody block in the README.md table.