Merge remote branch 'origin/master'
[ghc.git] / includes / rts / SpinLock.h
1 /* ----------------------------------------------------------------------------
2 *
3 * (c) The GHC Team, 2006-2009
4 *
5 * Spin locks
6 *
7 * These are simple spin-only locks as opposed to Mutexes which
8 * probably spin for a while before blocking in the kernel. We use
9 * these when we are sure that all our threads are actively running on
10 * a CPU, eg. in the GC.
11 *
12 * TODO: measure whether we really need these, or whether Mutexes
13 * would do (and be a bit safer if a CPU becomes loaded).
14 *
15 * Do not #include this file directly: #include "Rts.h" instead.
16 *
17 * To understand the structure of the RTS headers, see the wiki:
18 * http://hackage.haskell.org/trac/ghc/wiki/Commentary/SourceTree/Includes
19 *
20 * -------------------------------------------------------------------------- */
21
22 #ifndef RTS_SPINLOCK_H
23 #define RTS_SPINLOCK_H
24
25 #if defined(THREADED_RTS)
26
27 #if defined(PROF_SPIN)
28 typedef struct SpinLock_
29 {
30 StgWord lock;
31 StgWord64 spin; // DEBUG version counts how much it spins
32 } SpinLock;
33 #else
34 typedef StgWord SpinLock;
35 #endif
36
37 typedef StgWord SpinLockCount;
38
39 #if defined(PROF_SPIN)
40
41 // PROF_SPIN enables counting the number of times we spin on a lock
42
43 // acquire spin lock
44 INLINE_HEADER void ACQUIRE_SPIN_LOCK(SpinLock * p)
45 {
46 StgWord32 r = 0;
47 nat i;
48 do {
49 for (i = 0; i < SPIN_COUNT; i++) {
50 r = cas((StgVolatilePtr)&(p->lock), 1, 0);
51 if (r != 0) return;
52 p->spin++;
53 busy_wait_nop();
54 }
55 yieldThread();
56 } while (1);
57 }
58
59 // release spin lock
60 INLINE_HEADER void RELEASE_SPIN_LOCK(SpinLock * p)
61 {
62 write_barrier();
63 p->lock = 1;
64 }
65
66 // initialise spin lock
67 INLINE_HEADER void initSpinLock(SpinLock * p)
68 {
69 write_barrier();
70 p->lock = 1;
71 p->spin = 0;
72 }
73
74 #else
75
76 // acquire spin lock
77 INLINE_HEADER void ACQUIRE_SPIN_LOCK(SpinLock * p)
78 {
79 StgWord32 r = 0;
80 nat i;
81 do {
82 for (i = 0; i < SPIN_COUNT; i++) {
83 r = cas((StgVolatilePtr)p, 1, 0);
84 if (r != 0) return;
85 busy_wait_nop();
86 }
87 yieldThread();
88 } while (1);
89 }
90
91 // release spin lock
92 INLINE_HEADER void RELEASE_SPIN_LOCK(SpinLock * p)
93 {
94 write_barrier();
95 (*p) = 1;
96 }
97
98 // init spin lock
99 INLINE_HEADER void initSpinLock(SpinLock * p)
100 {
101 write_barrier();
102 (*p) = 1;
103 }
104
105 #endif /* PROF_SPIN */
106
107 #else /* !THREADED_RTS */
108
109 // Using macros here means we don't have to ensure the argument is in scope
110 #define ACQUIRE_SPIN_LOCK(p) /* nothing */
111 #define RELEASE_SPIN_LOCK(p) /* nothing */
112
113 INLINE_HEADER void initSpinLock(void * p STG_UNUSED)
114 { /* nothing */ }
115
116 #endif /* THREADED_RTS */
117
118 #endif /* RTS_SPINLOCK_H */
119