Update some atomic memory ordering
[openal-soft.git] / common / rwlock.c
blobcfa3aee4e19cdecb31eb108d24817051449efb7a
2 #include "config.h"
4 #include "rwlock.h"
6 #include "bool.h"
7 #include "atomic.h"
8 #include "threads.h"
11 /* A simple spinlock. Yield the thread while the given integer is set by
12 * another. Could probably be improved... */
13 #define LOCK(l) do { \
14 while(ATOMIC_EXCHANGE(int, &(l), true) == true) \
15 althrd_yield(); \
16 } while(0)
17 #define UNLOCK(l) ATOMIC_STORE(&(l), false)
20 void RWLockInit(RWLock *lock)
22 InitRef(&lock->read_count, 0);
23 InitRef(&lock->write_count, 0);
24 ATOMIC_INIT(&lock->read_lock, false);
25 ATOMIC_INIT(&lock->read_entry_lock, false);
26 ATOMIC_INIT(&lock->write_lock, false);
29 void ReadLock(RWLock *lock)
31 LOCK(lock->read_entry_lock);
32 LOCK(lock->read_lock);
33 if(IncrementRef(&lock->read_count) == 1)
34 LOCK(lock->write_lock);
35 UNLOCK(lock->read_lock);
36 UNLOCK(lock->read_entry_lock);
39 void ReadUnlock(RWLock *lock)
41 if(DecrementRef(&lock->read_count) == 0)
42 UNLOCK(lock->write_lock);
45 void WriteLock(RWLock *lock)
47 if(IncrementRef(&lock->write_count) == 1)
48 LOCK(lock->read_lock);
49 LOCK(lock->write_lock);
52 void WriteUnlock(RWLock *lock)
54 UNLOCK(lock->write_lock);
55 if(DecrementRef(&lock->write_count) == 0)
56 UNLOCK(lock->read_lock);