1 | // |
2 | // ScopedLock.h |
3 | // |
4 | // Library: Foundation |
5 | // Package: Threading |
6 | // Module: Mutex |
7 | // |
8 | // Definition of the ScopedLock template class. |
9 | // |
10 | // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. |
11 | // and Contributors. |
12 | // |
13 | // SPDX-License-Identifier: BSL-1.0 |
14 | // |
15 | |
16 | |
17 | #ifndef Foundation_ScopedLock_INCLUDED |
18 | #define Foundation_ScopedLock_INCLUDED |
19 | |
20 | |
21 | #include "Poco/Foundation.h" |
22 | |
23 | |
24 | namespace Poco { |
25 | |
26 | |
27 | template <class M> |
28 | class ScopedLock |
29 | /// A class that simplifies thread synchronization |
30 | /// with a mutex. |
31 | /// The constructor accepts a Mutex (and optionally |
32 | /// a timeout value in milliseconds) and locks it. |
33 | /// The destructor unlocks the mutex. |
34 | { |
35 | public: |
36 | explicit ScopedLock(M& mtx): _mutex(mtx) |
37 | { |
38 | _mutex.lock(); |
39 | } |
40 | |
41 | ScopedLock(M& mutex, long milliseconds): _mutex(mutex) |
42 | { |
43 | _mutex.lock(milliseconds); |
44 | } |
45 | |
46 | ~ScopedLock() |
47 | { |
48 | try |
49 | { |
50 | _mutex.unlock(); |
51 | } |
52 | catch (...) |
53 | { |
54 | poco_unexpected(); |
55 | } |
56 | } |
57 | |
58 | private: |
59 | M& _mutex; |
60 | |
61 | ScopedLock(); |
62 | ScopedLock(const ScopedLock&); |
63 | ScopedLock& operator = (const ScopedLock&); |
64 | }; |
65 | |
66 | |
67 | template <class M> |
68 | class ScopedLockWithUnlock |
69 | /// A class that simplifies thread synchronization |
70 | /// with a mutex. |
71 | /// The constructor accepts a Mutex (and optionally |
72 | /// a timeout value in milliseconds) and locks it. |
73 | /// The destructor unlocks the mutex. |
74 | /// The unlock() member function allows for manual |
75 | /// unlocking of the mutex. |
76 | { |
77 | public: |
78 | explicit ScopedLockWithUnlock(M& mutex): _pMutex(&mutex) |
79 | { |
80 | _pMutex->lock(); |
81 | } |
82 | |
83 | ScopedLockWithUnlock(M& mutex, long milliseconds): _pMutex(&mutex) |
84 | { |
85 | _pMutex->lock(milliseconds); |
86 | } |
87 | |
88 | ~ScopedLockWithUnlock() |
89 | { |
90 | try |
91 | { |
92 | unlock(); |
93 | } |
94 | catch (...) |
95 | { |
96 | poco_unexpected(); |
97 | } |
98 | } |
99 | |
100 | void unlock() |
101 | { |
102 | if (_pMutex) |
103 | { |
104 | _pMutex->unlock(); |
105 | _pMutex = 0; |
106 | } |
107 | } |
108 | |
109 | private: |
110 | M* _pMutex; |
111 | |
112 | ScopedLockWithUnlock(); |
113 | ScopedLockWithUnlock(const ScopedLockWithUnlock&); |
114 | ScopedLockWithUnlock& operator = (const ScopedLockWithUnlock&); |
115 | }; |
116 | |
117 | |
118 | } // namespace Poco |
119 | |
120 | |
121 | #endif // Foundation_ScopedLock_INCLUDED |
122 | |