cpp: Use #pragma once instead of #ifndef guards
[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 #pragma once
23
24 #if defined(THREADED_RTS)
25
26 #if defined(PROF_SPIN)
27 typedef struct SpinLock_
28 {
29 StgWord lock;
30 StgWord64 spin; // DEBUG version counts how much it spins
31 } SpinLock;
32 #else
33 typedef StgWord SpinLock;
34 #endif
35
36 #if defined(PROF_SPIN)
37
38 // PROF_SPIN enables counting the number of times we spin on a lock
39
40 // acquire spin lock
41 INLINE_HEADER void ACQUIRE_SPIN_LOCK(SpinLock * p)
42 {
43 StgWord32 r = 0;
44 uint32_t i;
45 do {
46 for (i = 0; i < SPIN_COUNT; i++) {
47 r = cas((StgVolatilePtr)&(p->lock), 1, 0);
48 if (r != 0) return;
49 p->spin++;
50 busy_wait_nop();
51 }
52 yieldThread();
53 } while (1);
54 }
55
56 // release spin lock
57 INLINE_HEADER void RELEASE_SPIN_LOCK(SpinLock * p)
58 {
59 write_barrier();
60 p->lock = 1;
61 }
62
63 // initialise spin lock
64 INLINE_HEADER void initSpinLock(SpinLock * p)
65 {
66 write_barrier();
67 p->lock = 1;
68 p->spin = 0;
69 }
70
71 #else
72
73 // acquire spin lock
74 INLINE_HEADER void ACQUIRE_SPIN_LOCK(SpinLock * p)
75 {
76 StgWord32 r = 0;
77 uint32_t i;
78 do {
79 for (i = 0; i < SPIN_COUNT; i++) {
80 r = cas((StgVolatilePtr)p, 1, 0);
81 if (r != 0) return;
82 busy_wait_nop();
83 }
84 yieldThread();
85 } while (1);
86 }
87
88 // release spin lock
89 INLINE_HEADER void RELEASE_SPIN_LOCK(SpinLock * p)
90 {
91 write_barrier();
92 (*p) = 1;
93 }
94
95 // init spin lock
96 INLINE_HEADER void initSpinLock(SpinLock * p)
97 {
98 write_barrier();
99 (*p) = 1;
100 }
101
102 #endif /* PROF_SPIN */
103
104 #else /* !THREADED_RTS */
105
106 // Using macros here means we don't have to ensure the argument is in scope
107 #define ACQUIRE_SPIN_LOCK(p) /* nothing */
108 #define RELEASE_SPIN_LOCK(p) /* nothing */
109
110 INLINE_HEADER void initSpinLock(void * p STG_UNUSED)
111 { /* nothing */ }
112
113 #endif /* THREADED_RTS */