SpinLock.h 2.09 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* ----------------------------------------------------------------------------
 *
 * (c) The GHC Team, 2006-2008
 *
 * Spin locks
 *
 * These are simple spin-only locks as opposed to Mutexes which
 * probably spin for a while before blocking in the kernel.  We use
 * these when we are sure that all our threads are actively running on
 * a CPU, eg. in the GC.
 *
 * TODO: measure whether we really need these, or whether Mutexes
 * would do (and be a bit safer if a CPU becomes loaded).
 *
 * -------------------------------------------------------------------------- */

#ifndef SPINLOCK_H
#define SPINLOCK_H
 
#if defined(THREADED_RTS)

22
23
#if defined(PROF_SPIN)
typedef struct SpinLock_
24
{
25
    StgWord   lock;
26
    StgWord64 spin; // DEBUG version counts how much it spins
27
} SpinLock;
28
#else
29
typedef StgWord SpinLock;
30
31
#endif

32
typedef lnat SpinLockCount;
33
34


35
#if defined(PROF_SPIN)
36

37
// PROF_SPIN enables counting the number of times we spin on a lock
38
39

// acquire spin lock
40
INLINE_HEADER void ACQUIRE_SPIN_LOCK(SpinLock * p)
41
42
{
    StgWord32 r = 0;
43
44
45
spin:
    r = cas((StgVolatilePtr)&(p->lock), 1, 0);
    if (r == 0) {
46
        p->spin++;
47
48
        goto spin;
    }
49
50
51
}

// release spin lock
52
INLINE_HEADER void RELEASE_SPIN_LOCK(SpinLock * p)
53
54
55
56
57
58
{
    write_barrier();
    p->lock = 1;
}

// initialise spin lock
59
INLINE_HEADER void initSpinLock(SpinLock * p)
60
61
62
63
64
65
66
67
68
{
    write_barrier();
    p->lock = 1;
    p->spin = 0;
}

#else

// acquire spin lock
69
INLINE_HEADER void ACQUIRE_SPIN_LOCK(SpinLock * p)
70
71
72
73
74
75
76
77
{
    StgWord32 r = 0;
    do {
        r = cas((StgVolatilePtr)p, 1, 0);
    } while(r == 0);
}

// release spin lock
78
INLINE_HEADER void RELEASE_SPIN_LOCK(SpinLock * p)
79
80
81
82
83
84
{
    write_barrier();
    (*p) = 1;
}

// init spin lock
85
INLINE_HEADER void initSpinLock(SpinLock * p)
86
87
88
89
90
{
    write_barrier();
    (*p) = 1;
}

91
#endif /* PROF_SPIN */
92
93
94
95
96
97
98
99
100
101
102
103
104
105

#else /* !THREADED_RTS */

// Using macros here means we don't have to ensure the argument is in scope
#define ACQUIRE_SPIN_LOCK(p) /* nothing */
#define RELEASE_SPIN_LOCK(p) /* nothing */

INLINE_HEADER void initSpinLock(void * p STG_UNUSED)
{ /* nothing */ }

#endif /* THREADED_RTS */

#endif /* SPINLOCK_H */