[ci skip] includes: detabify/dewhitespace rts/Hpc.h
[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://ghc.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 #if defined(PROF_SPIN)
38
39 // PROF_SPIN enables counting the number of times we spin on a lock
40
41 // acquire spin lock
42 INLINE_HEADER void ACQUIRE_SPIN_LOCK(SpinLock * p)
43 {
44 StgWord32 r = 0;
45 nat i;
46 do {
47 for (i = 0; i < SPIN_COUNT; i++) {
48 r = cas((StgVolatilePtr)&(p->lock), 1, 0);
49 if (r != 0) return;
50 p->spin++;
51 busy_wait_nop();
52 }
53 yieldThread();
54 } while (1);
55 }
56
57 // release spin lock
58 INLINE_HEADER void RELEASE_SPIN_LOCK(SpinLock * p)
59 {
60 write_barrier();
61 p->lock = 1;
62 }
63
64 // initialise spin lock
65 INLINE_HEADER void initSpinLock(SpinLock * p)
66 {
67 write_barrier();
68 p->lock = 1;
69 p->spin = 0;
70 }
71
72 #else
73
74 // acquire spin lock
75 INLINE_HEADER void ACQUIRE_SPIN_LOCK(SpinLock * p)
76 {
77 StgWord32 r = 0;
78 nat i;
79 do {
80 for (i = 0; i < SPIN_COUNT; i++) {
81 r = cas((StgVolatilePtr)p, 1, 0);
82 if (r != 0) return;
83 busy_wait_nop();
84 }
85 yieldThread();
86 } while (1);
87 }
88
89 // release spin lock
90 INLINE_HEADER void RELEASE_SPIN_LOCK(SpinLock * p)
91 {
92 write_barrier();
93 (*p) = 1;
94 }
95
96 // init spin lock
97 INLINE_HEADER void initSpinLock(SpinLock * p)
98 {
99 write_barrier();
100 (*p) = 1;
101 }
102
103 #endif /* PROF_SPIN */
104
105 #else /* !THREADED_RTS */
106
107 // Using macros here means we don't have to ensure the argument is in scope
108 #define ACQUIRE_SPIN_LOCK(p) /* nothing */
109 #define RELEASE_SPIN_LOCK(p) /* nothing */
110
111 INLINE_HEADER void initSpinLock(void * p STG_UNUSED)
112 { /* nothing */ }
113
114 #endif /* THREADED_RTS */
115
116 #endif /* RTS_SPINLOCK_H */
117