Skip to content

Improved SpinLock: spin on a load, yield after spinning, added try_lock - #87

Open
Haititi wants to merge 1 commit into
wqking:masterfrom
Haititi:fix/spinlock-backoff
Open

Haititi wants to merge 1 commit into
wqking:masterfrom
Haititi:fix/spinlock-backoff

Conversation

@Haititi

@Haititi Haititi commented Oct 6, 2026

Copy link
Copy Markdown

The old SpinLock spun on test_and_set without any backoff, which keeps invalidating the cache line of the lock and burns the CPU when the lock is held for long or there are more threads than CPU cores. Now the waiting thread spins on a plain load and yields after a while. It also uses std::atomic instead of std::atomic_flag with ATOMIC_FLAG_INIT, which is deprecated in C++20. Added try_lock so SpinLock satisfies Lockable.

Added unit tests and updated documents.

The old SpinLock spun on test_and_set without any backoff, which keeps invalidating the
cache line of the lock and burns the CPU when the lock is held for long or there are more
threads than CPU cores. Now the waiting thread spins on a plain load and yields after a
while. It also uses std::atomic<bool> instead of std::atomic_flag with ATOMIC_FLAG_INIT,
which is deprecated in C++20. Added try_lock so SpinLock satisfies Lockable.

Added unit tests and updated documents.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant