Line | |
---|
1 | /* -*- C++ -*- */ |
---|
2 | |
---|
3 | #ifndef _RECURSIVELOCK_H_ |
---|
4 | #define _RECURSIVELOCK_H_ |
---|
5 | |
---|
6 | /** |
---|
7 | * @class RecursiveLockType |
---|
8 | * @brief Implements a recursive lock using some base lock representation. |
---|
9 | * @param BaseLock The base lock representation. |
---|
10 | */ |
---|
11 | |
---|
12 | namespace HL { |
---|
13 | |
---|
14 | template <class BaseLock> |
---|
15 | class RecursiveLockType : public BaseLock { |
---|
16 | public: |
---|
17 | |
---|
18 | inline RecursiveLockType (void); |
---|
19 | |
---|
20 | inline void lock (void); |
---|
21 | inline void unlock (void); |
---|
22 | |
---|
23 | private: |
---|
24 | int tid; /// The lock owner's thread id. -1 if unlocked. |
---|
25 | int count; /// The recursion depth of the lock. |
---|
26 | }; |
---|
27 | |
---|
28 | |
---|
29 | }; |
---|
30 | |
---|
31 | template <class BaseLock> |
---|
32 | HL::RecursiveLockType<BaseLock>::RecursiveLockType (void) |
---|
33 | : tid (-1), |
---|
34 | count (0) |
---|
35 | {} |
---|
36 | |
---|
37 | template <class BaseLock> |
---|
38 | void HL::RecursiveLockType<BaseLock>::lock (void) { |
---|
39 | int currthread = GetCurrentThreadId(); |
---|
40 | if (tid == currthread) { |
---|
41 | count++; |
---|
42 | } else { |
---|
43 | BaseLock::lock(); |
---|
44 | tid = currthread; |
---|
45 | count++; |
---|
46 | } |
---|
47 | } |
---|
48 | |
---|
49 | template <class BaseLock> |
---|
50 | void HL::RecursiveLockType<BaseLock>::unlock (void) { |
---|
51 | int currthread = GetCurrentThreadId(); |
---|
52 | if (tid == currthread) { |
---|
53 | count--; |
---|
54 | if (count == 0) { |
---|
55 | tid = -1; |
---|
56 | BaseLock::unlock(); |
---|
57 | } |
---|
58 | } else { |
---|
59 | // We tried to unlock it but we didn't lock it! |
---|
60 | // This should never happen. |
---|
61 | assert (0); |
---|
62 | abort(); |
---|
63 | } |
---|
64 | } |
---|
65 | |
---|
66 | #endif |
---|
Note: See
TracBrowser
for help on using the repository browser.