Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SpinLock: Overhaul false sharing prevention #99168

Merged
merged 1 commit into from
Dec 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 27 additions & 6 deletions core/os/spin_lock.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,15 @@
#ifndef SPIN_LOCK_H
#define SPIN_LOCK_H

#include "core/os/thread.h"
#include "core/typedefs.h"

#ifdef THREADS_ENABLED

// Note the implementations below avoid false sharing by ensuring their
// sizes match the assumed cache line. We can't use align attributes
// because these objects may end up unaligned in semi-tightly packed arrays.

#ifdef _MSC_VER
#include <intrin.h>
#endif
Expand All @@ -42,7 +49,10 @@
#include <os/lock.h>

class SpinLock {
mutable os_unfair_lock _lock = OS_UNFAIR_LOCK_INIT;
union {
mutable os_unfair_lock _lock = OS_UNFAIR_LOCK_INIT;
char aligner[Thread::CACHE_LINE_BYTES];
};

public:
_ALWAYS_INLINE_ void lock() const {
Expand All @@ -54,9 +64,7 @@ class SpinLock {
}
};

#else

#include "core/os/thread.h"
#else // __APPLE__

#include <atomic>

Expand Down Expand Up @@ -84,8 +92,11 @@ _ALWAYS_INLINE_ static void _cpu_pause() {

static_assert(std::atomic_bool::is_always_lock_free);

class alignas(Thread::CACHE_LINE_BYTES) SpinLock {
mutable std::atomic<bool> locked = ATOMIC_VAR_INIT(false);
class SpinLock {
union {
mutable std::atomic<bool> locked = ATOMIC_VAR_INIT(false);
char aligner[Thread::CACHE_LINE_BYTES];
};

public:
_ALWAYS_INLINE_ void lock() const {
Expand All @@ -107,4 +118,14 @@ class alignas(Thread::CACHE_LINE_BYTES) SpinLock {

#endif // __APPLE__

#else // THREADS_ENABLED

class SpinLock {
public:
void lock() const {}
void unlock() const {}
};

#endif // THREADS_ENABLED

#endif // SPIN_LOCK_H