aboutsummaryrefslogtreecommitdiffstats
path: root/common/rwlock.c
blob: ff7aa4186e7ae9100f80a184e40e2590bfcfe8aa (plain)
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
60
61
62

#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... */
static void Lock(volatile int *l)
{
    while(ExchangeInt(l, true) == true)
        althrd_yield();
}

static void Unlock(volatile int *l)
{
    ExchangeInt(l, false);
}


void RWLockInit(RWLock *lock)
{
    InitRef(&lock->read_count, 0);
    InitRef(&lock->write_count, 0);
    lock->read_lock = false;
    lock->read_entry_lock = false;
    lock->write_lock = false;
}

void ReadLock(RWLock *lock)
{
    Lock(&lock->read_entry_lock);
    Lock(&lock->read_lock);
    if(IncrementRef(&lock->read_count) == 1)
        Lock(&lock->write_lock);
    Unlock(&lock->read_lock);
    Unlock(&lock->read_entry_lock);
}

void ReadUnlock(RWLock *lock)
{
    if(DecrementRef(&lock->read_count) == 0)
        Unlock(&lock->write_lock);
}

void WriteLock(RWLock *lock)
{
    if(IncrementRef(&lock->write_count) == 1)
        Lock(&lock->read_lock);
    Lock(&lock->write_lock);
}

void WriteUnlock(RWLock *lock)
{
    Unlock(&lock->write_lock);
    if(DecrementRef(&lock->write_count) == 0)
        Unlock(&lock->read_lock);
}