Tidy up file headers and copyrights; point to the wiki for docs
[ghc-hetmet.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 lnat SpinLockCount;
38
39
40 #if defined(PROF_SPIN)
41
42 // PROF_SPIN enables counting the number of times we spin on a lock
43
44 // acquire spin lock
45 INLINE_HEADER void ACQUIRE_SPIN_LOCK(SpinLock * p)
46 {
47     StgWord32 r = 0;
48 spin:
49     r = cas((StgVolatilePtr)&(p->lock), 1, 0);
50     if (r == 0) {
51         p->spin++;
52         goto spin;
53     }
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     do {
78         r = cas((StgVolatilePtr)p, 1, 0);
79     } while(r == 0);
80 }
81
82 // release spin lock
83 INLINE_HEADER void RELEASE_SPIN_LOCK(SpinLock * p)
84 {
85     write_barrier();
86     (*p) = 1;
87 }
88
89 // init spin lock
90 INLINE_HEADER void initSpinLock(SpinLock * p)
91 {
92     write_barrier();
93     (*p) = 1;
94 }
95
96 #endif /* PROF_SPIN */
97
98 #else /* !THREADED_RTS */
99
100 // Using macros here means we don't have to ensure the argument is in scope
101 #define ACQUIRE_SPIN_LOCK(p) /* nothing */
102 #define RELEASE_SPIN_LOCK(p) /* nothing */
103
104 INLINE_HEADER void initSpinLock(void * p STG_UNUSED)
105 { /* nothing */ }
106
107 #endif /* THREADED_RTS */
108
109 #endif /* RTS_SPINLOCK_H */
110