Skip to content

Commit a5729b7

Browse files
authored
[atomics] Initialize pthread_mutex_t and avoid false sharing
PTHREAD_MUTEX_INITIALIZER is zeroes for glibc and musl, but it improves conformance and might work with more libc implementations. Follow-up to #94374 Pull Request: #94387
1 parent 3b2df5b commit a5729b7

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

compiler-rt/lib/builtins/atomic.c

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,14 @@
5151
#endif
5252
static const long SPINLOCK_MASK = SPINLOCK_COUNT - 1;
5353

54+
#ifndef CACHE_LINE_SIZE
55+
#define CACHE_LINE_SIZE 64
56+
#endif
57+
58+
#ifdef __clang__
59+
#pragma clang diagnostic ignored "-Wgnu-designator"
60+
#endif
61+
5462
////////////////////////////////////////////////////////////////////////////////
5563
// Platform-specific lock implementation. Falls back to spinlocks if none is
5664
// defined. Each platform should define the Lock type, and corresponding
@@ -95,13 +103,17 @@ static Lock locks[SPINLOCK_COUNT]; // initialized to OS_SPINLOCK_INIT which is 0
95103
_Static_assert(__atomic_always_lock_free(sizeof(uintptr_t), 0),
96104
"Implementation assumes lock-free pointer-size cmpxchg");
97105
#include <pthread.h>
98-
typedef pthread_mutex_t Lock;
106+
#include <stdalign.h>
107+
typedef struct {
108+
alignas(CACHE_LINE_SIZE) pthread_mutex_t m;
109+
} Lock;
99110
/// Unlock a lock. This is a release operation.
100-
__inline static void unlock(Lock *l) { pthread_mutex_unlock(l); }
111+
__inline static void unlock(Lock *l) { pthread_mutex_unlock(&l->m); }
101112
/// Locks a lock.
102-
__inline static void lock(Lock *l) { pthread_mutex_lock(l); }
113+
__inline static void lock(Lock *l) { pthread_mutex_lock(&l->m); }
103114
/// locks for atomic operations
104-
static Lock locks[SPINLOCK_COUNT];
115+
static Lock locks[SPINLOCK_COUNT] = {
116+
[0 ... SPINLOCK_COUNT - 1] = {PTHREAD_MUTEX_INITIALIZER}};
105117
#endif
106118

107119
/// Returns a lock to use for a given pointer.

0 commit comments

Comments
 (0)