Skip to content

Commit f4bcfc7

Browse files
Merge pull request #247 from insertinterestingnamehere/trylock
Fix Non-Atomic Load In Trylock
2 parents 4b54807 + 7fd130b commit f4bcfc7

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

include/qt_atomics.h

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,18 +136,19 @@ extern pthread_mutexattr_t _fastlock_attr;
136136
# define QTHREAD_TRYLOCK_INIT(x) { (x).u = 0; }
137137
# define QTHREAD_TRYLOCK_INIT_PTR(x) { (x)->u = 0; }
138138
# define QTHREAD_TRYLOCK_LOCK(x) { uint32_t val = qthread_incr(&(x)->s.users, 1); \
139-
while (val != (x)->s.ticket) SPINLOCK_BODY(); \
140-
THREAD_FENCE_MEM_ACQUIRE; /* spin waiting for my turn */ }
139+
while (val != atomic_load_explicit((_Atomic uint32_t *)&(x)->s.ticket, memory_order_acquire)) SPINLOCK_BODY();}
141140
# define QTHREAD_TRYLOCK_UNLOCK(x) do { COMPILER_FENCE; \
142-
THREAD_FENCE_MEM_RELEASE; \
141+
THREAD_FENCE_MEM_RELEASE; \
143142
qthread_incr(&(x)->s.ticket, 1); /* allow next guy's turn */ \
144143
} while (0)
145144
# define QTHREAD_TRYLOCK_DESTROY(x)
146145
# define QTHREAD_TRYLOCK_DESTROY_PTR(x)
147146

148147
static inline int QTHREAD_TRYLOCK_TRY(qt_spin_trylock_t *x)
149148
{
150-
qt_spin_trylock_t newcmp, cmp = *(x);
149+
qt_spin_trylock_t newcmp, cmp;
150+
uint64_t tmp = atomic_load_explicit((_Atomic uint64_t*)x, memory_order_relaxed);
151+
cmp = *(qt_spin_trylock_t*)&tmp;
151152

152153
if (cmp.s.users != cmp.s.ticket) {
153154
return 0;
@@ -157,7 +158,6 @@ static inline int QTHREAD_TRYLOCK_TRY(qt_spin_trylock_t *x)
157158
newcmp.s.users = newcmp.s.ticket + 1;
158159

159160
if(qthread_cas(&(x->u), cmp.u, newcmp.u) == cmp.u) {
160-
THREAD_FENCE_MEM_ACQUIRE;
161161
return 1;
162162
}
163163
return 0;

0 commit comments

Comments
 (0)