1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
#include "config.h"
#include "rwlock.h"
#include "bool.h"
#include "atomic.h"
#include "threads.h"
/* A simple spinlock. Yield the thread while the given integer is set by
* another. Could probably be improved... */
#define LOCK(l) do { \
while(ATOMIC_EXCHANGE(&(l), 1, almemory_order_acq_rel) == true) \
althrd_yield(); \
} while(0)
#define UNLOCK(l) ATOMIC_STORE(&(l), 0, almemory_order_release)
void RWLockInit(RWLock *lock)
{
InitRef(&lock->read_count, 0);
InitRef(&lock->write_count, 0);
ATOMIC_INIT(&lock->read_lock, 0);
ATOMIC_INIT(&lock->read_entry_lock, 0);
ATOMIC_INIT(&lock->write_lock, 0);
}
void ReadLock(RWLock *lock)
{
LOCK(lock->read_entry_lock);
LOCK(lock->read_lock);
/* NOTE: ATOMIC_ADD returns the *old* value! */
if(ATOMIC_ADD(&lock->read_count, 1, almemory_order_acq_rel) == 0)
LOCK(lock->write_lock);
UNLOCK(lock->read_lock);
UNLOCK(lock->read_entry_lock);
}
void ReadUnlock(RWLock *lock)
{
/* NOTE: ATOMIC_SUB returns the *old* value! */
if(ATOMIC_SUB(&lock->read_count, 1, almemory_order_acq_rel) == 1)
UNLOCK(lock->write_lock);
}
void WriteLock(RWLock *lock)
{
if(ATOMIC_ADD(&lock->write_count, 1, almemory_order_acq_rel) == 0)
LOCK(lock->read_lock);
LOCK(lock->write_lock);
}
void WriteUnlock(RWLock *lock)
{
UNLOCK(lock->write_lock);
if(ATOMIC_SUB(&lock->write_count, 1, almemory_order_acq_rel) == 1)
UNLOCK(lock->read_lock);
}
|