Cope with libraries in libraries/foo/bar rather than just libraries/foo
[ghc-hetmet.git] / includes / SpinLock.h
1 /* ----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2006-2008
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  * -------------------------------------------------------------------------- */
16
17 #ifndef SPINLOCK_H
18 #define SPINLOCK_H
19  
20 #if defined(THREADED_RTS)
21
22 #if defined(DEBUG)
23 typedef struct StgSync_
24 {
25     StgWord32 lock;
26     StgWord64 spin; // DEBUG version counts how much it spins
27 } StgSync;
28 #else
29 typedef StgWord StgSync;
30 #endif
31
32 typedef lnat StgSyncCount;
33
34
35 #if defined(DEBUG)
36
37 // Debug versions of spin locks maintain a spin count
38
39 // How to use: 
40 //  To use the debug veriosn of the spin locks, a debug version of the program 
41 //  can be run under a deugger with a break point on stat_exit. At exit time 
42 //  of the program one can examine the state the spin count counts of various
43 //  spin locks to check for contention. 
44
45 // acquire spin lock
46 INLINE_HEADER void ACQUIRE_SPIN_LOCK(StgSync * p)
47 {
48     StgWord32 r = 0;
49     do {
50         p->spin++;
51         r = cas((StgVolatilePtr)&(p->lock), 1, 0);
52     } while(r == 0);
53     p->spin--;
54 }
55
56 // release spin lock
57 INLINE_HEADER void RELEASE_SPIN_LOCK(StgSync * p)
58 {
59     write_barrier();
60     p->lock = 1;
61 }
62
63 // initialise spin lock
64 INLINE_HEADER void initSpinLock(StgSync * 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(StgSync * 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(StgSync * p)
84 {
85     write_barrier();
86     (*p) = 1;
87 }
88
89 // init spin lock
90 INLINE_HEADER void initSpinLock(StgSync * p)
91 {
92     write_barrier();
93     (*p) = 1;
94 }
95
96 #endif /* DEBUG */
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 /* SPINLOCK_H */
110