solidc
Robust collection of general-purpose cross-platform C libraries and data structures designed for rapid and safe development in C
Loading...
Searching...
No Matches
spinlock.h
Go to the documentation of this file.
1
27#ifndef SPINLOCK_H
28#define SPINLOCK_H
29
30#ifdef __cplusplus
31#include <atomic>
32extern "C" {
33#else
34#include <stdatomic.h>
35#endif
36
37#if defined(__x86_64__) || defined(__i386__)
38#include <emmintrin.h> // For _mm_pause on x86
39#endif
40
49typedef struct {
51#ifdef __cplusplus
52 std::atomic<int> state;
53#else
54 _Atomic(int) state;
55#endif
57
73static inline void cpu_relax(void) {
74#if defined(__x86_64__) || defined(__i386__)
75 _mm_pause();
76#elif defined(__aarch64__) || defined(__arm__)
77 __asm__ volatile("yield");
78#else
79 /* No-op on other platforms */
80#endif
81}
82
100static inline void fast_rwlock_init(fast_rwlock_t* l) {
101#ifdef __cplusplus
102 new (&l->state) std::atomic<int>(0);
103#else
104 atomic_init(&l->state, 0);
105#endif
106}
107
133static inline void fast_rwlock_rdlock(fast_rwlock_t* l) {
134 while (true) {
135#ifdef __cplusplus
136 int state = l->state.load(std::memory_order_relaxed);
137#else
138 int state = atomic_load_explicit(&l->state, memory_order_relaxed);
139#endif
140 if (state < 0) {
141 cpu_relax();
142 continue;
143 }
144#ifdef __cplusplus
145 if (l->state.compare_exchange_weak(state, state + 1, std::memory_order_acquire, std::memory_order_relaxed))
146#else
147 if (atomic_compare_exchange_weak_explicit(&l->state, &state, state + 1, memory_order_acquire,
148 memory_order_relaxed))
149#endif
150 return;
151 cpu_relax();
152 }
153}
154
178static inline void fast_rwlock_unlock_rd(fast_rwlock_t* l) {
179#ifdef __cplusplus
180 l->state.fetch_sub(1, std::memory_order_release);
181#else
182 atomic_fetch_sub_explicit(&l->state, 1, memory_order_release);
183#endif
184}
185
212static inline void fast_rwlock_wrlock(fast_rwlock_t* l) {
213 while (true) {
214 int expected = 0;
215#ifdef __cplusplus
216 if (l->state.compare_exchange_weak(expected, -1, std::memory_order_acquire, std::memory_order_relaxed))
217#else
218 if (atomic_compare_exchange_weak_explicit(&l->state, &expected, -1, memory_order_acquire, memory_order_relaxed))
219#endif
220 return;
221 cpu_relax();
222 }
223}
224
248static inline void fast_rwlock_unlock_wr(fast_rwlock_t* l) {
249#ifdef __cplusplus
250 l->state.store(0, std::memory_order_release);
251#else
252 atomic_store_explicit(&l->state, 0, memory_order_release);
253#endif
254}
255
256#ifdef __cplusplus
257}
258#endif
259
260#endif // SPINLOCK_H
Reader-writer spinlock structure.
Definition spinlock.h:49
_Atomic(int) state