
Spinlocks vs Mutexes: When Spinning Wins
A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.
Tag
31 posts

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

Use C++17's std::hardware_destructive_interference_size to pad against false sharing, with the feature-test macro, the GCC warning and a safe fallback constant.

Fix false sharing in C++17 by giving each thread's data its own cache line with alignas(64), explicit padding, static_assert checks and aligned heap allocation.

Amdahl's law caps parallel speedup at one over the serial fraction. Work the numbers in C and see why a 95 percent parallel program tops out at 20 times.

False sharing makes threads that write different variables slow each other down because they share a cache line. See it in a four-thread C counter.

Control hyperfine 1.19 with --warmup, --prepare, --setup, --cleanup and --parameter-scan to measure cold and warm runs and sweep threads or compilers.

Build Google Benchmark 1.9, write a first BM_ function with the state loop, read the Time, CPU and Iterations columns, and avoid beginner traps.

Benchmark any command with hyperfine 1.19: it runs warm-ups and many repetitions, reports mean, spread and range, and compares commands against each other.

A timing loop around a function can report zero, the wrong function or noise. Learn seven mistakes that make native benchmarks lie, with fixes.

Create a command pool, record a vkCmdFillBuffer into a command buffer, submit it with a fence, and read the result back from host-visible memory in C++.

Avoid lock-ordering deadlocks in C++17 and C++20 by locking several mutexes at once with std::scoped_lock, with a bank transfer example and the pitfalls.

Replace GNU attribute spellings with standard [[nodiscard]], [[maybe_unused]], [[deprecated]] and [[fallthrough]] in C23 and C++17, and see what GCC reports.