Created
March 18, 2026 00:54
-
-
Save rdmsr/9188066462ab7039b60c09b10c25a75b to your computer and use it in GitHub Desktop.
qspinlock, spinlock and ticket spinlock benchmarks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <algorithm> | |
| #include <atomic> | |
| #include <chrono> | |
| #include <cstdint> | |
| #include <iostream> | |
| #include <memory> | |
| #include <thread> | |
| #include <vector> | |
| #ifdef __linux__ | |
| #include <pthread.h> | |
| #include <sched.h> | |
| #include <unistd.h> | |
| #endif | |
| struct McsNode { | |
| std::atomic<McsNode *> next{nullptr}; | |
| std::atomic<int> locked{0}; | |
| }; | |
| struct Cpu { | |
| int id; | |
| int curr_idx; | |
| McsNode qnodes[4]; | |
| }; | |
| thread_local Cpu *my_cpu = nullptr; | |
| Cpu **cpus = nullptr; | |
| static std::vector<std::unique_ptr<Cpu>> cpu_storage; | |
| static int g_ncpu = 1; | |
| #if defined(__x86_64__) || defined(__i386__) | |
| #include <immintrin.h> | |
| static inline void cpu_relax() { _mm_pause(); } | |
| #else | |
| static inline void cpu_relax() { std::this_thread::yield(); } | |
| #endif | |
| static constexpr uint32_t MAX_IDX = 4; | |
| struct QSpinLock { | |
| static constexpr uint32_t LOCKED_MASK = 0x000000FF; | |
| static constexpr uint32_t LOCKED_VAL = 0x00000001; | |
| static constexpr uint32_t PENDING_MASK = 0x0000FF00; | |
| static constexpr uint32_t PENDING_VAL = 0x00000100; | |
| static constexpr uint32_t TAIL_IDX_MASK = 0x00030000; | |
| static constexpr uint32_t TAIL_CPU_MASK = 0xFFFC0000; | |
| static constexpr uint32_t TAIL_MASK = TAIL_IDX_MASK | TAIL_CPU_MASK; | |
| static constexpr uint32_t TAIL_IDX_OFFSET = 16; | |
| static constexpr uint32_t TAIL_CPU_OFFSET = 18; | |
| static constexpr uint32_t PENDING_LOOPS = 512; | |
| union { | |
| std::atomic<uint32_t> val; | |
| struct { | |
| std::atomic<uint8_t> locked; | |
| std::atomic<uint8_t> pending; | |
| } low_word; | |
| struct { | |
| std::atomic<uint16_t> locked_pending; | |
| std::atomic<uint16_t> tail; | |
| } split; | |
| }; | |
| void reset() { val.store(0, std::memory_order_relaxed); } | |
| static uint32_t encode_tail(uint32_t cpu_id, uint32_t idx) { | |
| return ((cpu_id + 1) << TAIL_CPU_OFFSET) | (idx << TAIL_IDX_OFFSET); | |
| } | |
| static McsNode *decode_tail(uint32_t tail) { | |
| uint32_t cpu_id = (tail >> TAIL_CPU_OFFSET) - 1; | |
| uint32_t idx = (tail & TAIL_IDX_MASK) >> TAIL_IDX_OFFSET; | |
| return &cpus[cpu_id]->qnodes[idx]; | |
| } | |
| bool try_lock() { | |
| uint32_t expected = 0; | |
| return val.compare_exchange_strong(expected, LOCKED_VAL, | |
| std::memory_order_acquire, | |
| std::memory_order_acquire); | |
| } | |
| uint32_t xchg_tail(uint32_t tail) { | |
| uint16_t tail16 = tail >> 16; | |
| uint16_t old_tail16 = | |
| split.tail.exchange(tail16, std::memory_order_acq_rel); | |
| return static_cast<uint32_t>(old_tail16) << 16; | |
| } | |
| void queue() { | |
| uint32_t idx = my_cpu->curr_idx++; | |
| struct IdxGuard { | |
| int &v; | |
| ~IdxGuard() { --v; } | |
| } guard{my_cpu->curr_idx}; | |
| if (idx >= MAX_IDX) { | |
| while (!try_lock()) | |
| cpu_relax(); | |
| return; | |
| } | |
| McsNode *node = &cpus[my_cpu->id]->qnodes[idx]; | |
| node->locked.store(0, std::memory_order_relaxed); | |
| node->next.store(nullptr, std::memory_order_relaxed); | |
| // It's been a while, try again | |
| if (try_lock()) { | |
| return; | |
| } | |
| std::atomic_thread_fence(std::memory_order_release); | |
| uint32_t tail = encode_tail(my_cpu->id, idx); | |
| uint32_t old = xchg_tail(tail); | |
| // Someone else was already waiting, set their next | |
| if (old & TAIL_MASK) { | |
| McsNode *prev = decode_tail(old); | |
| prev->next.store(node, std::memory_order_release); | |
| while (node->locked.load(std::memory_order_acquire) == 0) { | |
| cpu_relax(); | |
| } | |
| } | |
| uint32_t v = 0; | |
| while (((v = val.load(std::memory_order_acquire)) & | |
| (LOCKED_MASK | PENDING_MASK)) != 0) { | |
| cpu_relax(); | |
| } | |
| // If we're the only waiter, try to claim calmly | |
| // n, 0, 0 -> 0, 0, 1 | |
| if ((v & TAIL_MASK) == tail) { | |
| uint32_t expected = v; | |
| if (val.compare_exchange_strong(expected, LOCKED_VAL, | |
| std::memory_order_acquire, | |
| std::memory_order_relaxed)) { | |
| // No contention, we're done | |
| return; | |
| } | |
| } | |
| low_word.locked.store(1, std::memory_order_release); | |
| McsNode *next = nullptr; | |
| while ((next = node->next.load(std::memory_order_acquire)) == nullptr) { | |
| cpu_relax(); | |
| } | |
| next->locked.store(1, std::memory_order_release); | |
| } | |
| void lock() { | |
| uint32_t v = 0; | |
| if (val.compare_exchange_strong(v, LOCKED_VAL, std::memory_order_acquire, | |
| std::memory_order_relaxed)) { | |
| return; | |
| } | |
| if (v == PENDING_VAL) { | |
| uint32_t cnt = PENDING_LOOPS; | |
| while (cnt--) { | |
| v = val.load(std::memory_order_relaxed); | |
| if (v != PENDING_VAL) | |
| break; | |
| cpu_relax(); | |
| } | |
| } | |
| if (v & ~LOCKED_MASK) { | |
| queue(); | |
| return; | |
| } | |
| v = val.fetch_or(PENDING_VAL, std::memory_order_acquire); | |
| if (v & ~LOCKED_MASK) [[unlikely]] { | |
| if ((v & PENDING_MASK) == 0) { | |
| val.fetch_and(~PENDING_VAL, std::memory_order_release); | |
| } | |
| queue(); | |
| return; | |
| } | |
| if (v & LOCKED_MASK) { | |
| while (low_word.locked.load(std::memory_order_acquire) != 0) { | |
| cpu_relax(); | |
| } | |
| } | |
| // clear pending and set locked | |
| split.locked_pending.store(1, std::memory_order_release); | |
| } | |
| void unlock() { low_word.locked.store(0, std::memory_order_release); } | |
| }; | |
| struct SpinLock { | |
| std::atomic<uint32_t> v{0}; | |
| void lock() { | |
| for (;;) { | |
| uint32_t expected = 0; | |
| if (v.compare_exchange_weak(expected, 1, std::memory_order_acquire, | |
| std::memory_order_relaxed)) | |
| return; | |
| while (v.load(std::memory_order_relaxed) != 0) | |
| cpu_relax(); | |
| } | |
| } | |
| void unlock() { v.store(0, std::memory_order_release); } | |
| }; | |
| struct TicketLock { | |
| std::atomic<uint32_t> next{0}; | |
| std::atomic<uint32_t> owner{0}; | |
| void lock() { | |
| const uint32_t my = next.fetch_add(1, std::memory_order_relaxed); | |
| while (owner.load(std::memory_order_acquire) != my) | |
| cpu_relax(); | |
| } | |
| void unlock() { owner.fetch_add(1, std::memory_order_release); } | |
| }; | |
| static void pin_thread(int tid) { | |
| #ifdef __linux__ | |
| cpu_set_t set; | |
| CPU_ZERO(&set); | |
| CPU_SET(tid % g_ncpu, &set); | |
| pthread_setaffinity_np(pthread_self(), sizeof(set), &set); | |
| #endif | |
| my_cpu = cpus[tid % g_ncpu]; | |
| my_cpu->curr_idx = 0; | |
| } | |
| template <typename LockT> static double run_once(int num_threads) { | |
| constexpr int OPS_PER_THREAD = 500'000; | |
| const int total_ops = OPS_PER_THREAD * num_threads; | |
| LockT lock{}; | |
| std::vector<int> shared_vector; | |
| shared_vector.reserve(total_ops); | |
| std::vector<std::thread> threads; | |
| std::atomic<int> ready{0}; | |
| std::atomic<bool> start{false}; | |
| for (int i = 0; i < num_threads; ++i) { | |
| threads.emplace_back([&, i] { | |
| pin_thread(i); | |
| ready.fetch_add(1, std::memory_order_release); | |
| while (!start.load(std::memory_order_acquire)) | |
| cpu_relax(); | |
| for (int j = 0; j < OPS_PER_THREAD; ++j) { | |
| lock.lock(); | |
| shared_vector.push_back(j); | |
| lock.unlock(); | |
| } | |
| }); | |
| } | |
| while (ready.load(std::memory_order_acquire) != num_threads) | |
| cpu_relax(); | |
| auto t0 = std::chrono::steady_clock::now(); | |
| start.store(true, std::memory_order_release); | |
| for (auto &t : threads) | |
| t.join(); | |
| auto t1 = std::chrono::steady_clock::now(); | |
| std::chrono::duration<double> duration = t1 - t0; | |
| return duration.count(); | |
| } | |
| template <typename LockT> | |
| static void run_benchmark(const char *lock_name, int num_threads, | |
| int num_samples = 5) { | |
| constexpr int OPS_PER_THREAD = 500'000; | |
| const int total_ops = OPS_PER_THREAD * num_threads; | |
| // warmup run | |
| run_once<LockT>(num_threads); | |
| std::vector<double> times; | |
| times.reserve(num_samples); | |
| for (int s = 0; s < num_samples; s++) | |
| times.push_back(run_once<LockT>(num_threads)); | |
| std::sort(times.begin(), times.end()); | |
| double median = times[num_samples / 2]; | |
| std::cout << lock_name << "," << num_threads << "," << static_cast<uint64_t>(total_ops / median) | |
| << "\n"; | |
| } | |
| int main() { | |
| #ifdef __linux__ | |
| g_ncpu = std::max(1, static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN))); | |
| #else | |
| g_ncpu = std::max(1u, std::thread::hardware_concurrency()); | |
| #endif | |
| cpu_storage.reserve(g_ncpu); | |
| for (int i = 0; i < g_ncpu; ++i) { | |
| auto c = std::make_unique<Cpu>(); | |
| c->id = i; | |
| c->curr_idx = 0; | |
| for (auto &n : c->qnodes) { | |
| n.next.store(nullptr, std::memory_order_relaxed); | |
| n.locked.store(0, std::memory_order_relaxed); | |
| } | |
| cpu_storage.push_back(std::move(c)); | |
| } | |
| cpus = new Cpu *[g_ncpu]; | |
| for (int i = 0; i < g_ncpu; ++i) | |
| cpus[i] = cpu_storage[i].get(); | |
| std::vector<int> thread_counts = {1, 2, 4, 8, 12}; | |
| for (int t : thread_counts) { | |
| run_benchmark<SpinLock>("spinlock", t); | |
| run_benchmark<TicketLock>("ticket_spinlock", t); | |
| run_benchmark<QSpinLock>("qspinlock", t); | |
| } | |
| delete[] cpus; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment