Chris@16
|
1 // Copyright (C) 2000 Stephen Cleary
|
Chris@16
|
2 //
|
Chris@16
|
3 // Distributed under the Boost Software License, Version 1.0. (See
|
Chris@16
|
4 // accompanying file LICENSE_1_0.txt or copy at
|
Chris@16
|
5 // http://www.boost.org/LICENSE_1_0.txt)
|
Chris@16
|
6 //
|
Chris@16
|
7 // See http://www.boost.org for updates, documentation, and revision history.
|
Chris@16
|
8
|
Chris@16
|
9 #ifndef BOOST_POOL_GUARD_HPP
|
Chris@16
|
10 #define BOOST_POOL_GUARD_HPP
|
Chris@16
|
11
|
Chris@16
|
12 /*!
|
Chris@16
|
13 \file
|
Chris@16
|
14 \brief Extremely Light-Weight guard class.
|
Chris@16
|
15 \details Auto-lock/unlock-er
|
Chris@16
|
16 detail/guard.hpp provides a type guard<Mutex>
|
Chris@16
|
17 that allows scoped access to the Mutex's locking and unlocking operations.
|
Chris@16
|
18 It is used to ensure that a Mutex is unlocked, even if an exception is thrown.
|
Chris@16
|
19 */
|
Chris@16
|
20
|
Chris@16
|
21 namespace boost {
|
Chris@16
|
22
|
Chris@16
|
23 namespace details {
|
Chris@16
|
24 namespace pool {
|
Chris@16
|
25
|
Chris@16
|
26 template <typename Mutex> //!< \tparam Mutex (platform-specific) mutex class.
|
Chris@16
|
27 class guard
|
Chris@16
|
28 { //! Locks the mutex, binding guard<Mutex> to Mutex.
|
Chris@16
|
29 /*! Example:
|
Chris@16
|
30 Given a (platform-specific) mutex class, we can wrap code as follows:
|
Chris@16
|
31
|
Chris@16
|
32 extern mutex global_lock;
|
Chris@16
|
33
|
Chris@16
|
34 static void f()
|
Chris@16
|
35 {
|
Chris@16
|
36 boost::details::pool::guard<mutex> g(global_lock);
|
Chris@16
|
37 // g's constructor locks "global_lock"
|
Chris@16
|
38
|
Chris@16
|
39 ... // do anything:
|
Chris@16
|
40 // throw exceptions
|
Chris@16
|
41 // return
|
Chris@16
|
42 // or just fall through
|
Chris@16
|
43 } // g's destructor unlocks "global_lock"
|
Chris@16
|
44 */
|
Chris@16
|
45 private:
|
Chris@16
|
46 Mutex & mtx;
|
Chris@16
|
47
|
Chris@16
|
48 guard(const guard &); //!< Guards the mutex, ensuring unlocked on destruction, even if exception is thrown.
|
Chris@16
|
49 void operator=(const guard &);
|
Chris@16
|
50
|
Chris@16
|
51 public:
|
Chris@16
|
52 explicit guard(Mutex & nmtx)
|
Chris@16
|
53 :mtx(nmtx)
|
Chris@16
|
54 { //! Locks the mutex of the guard class.
|
Chris@16
|
55 mtx.lock();
|
Chris@16
|
56 }
|
Chris@16
|
57
|
Chris@16
|
58 ~guard()
|
Chris@16
|
59 { //! destructor unlocks the mutex of the guard class.
|
Chris@16
|
60 mtx.unlock();
|
Chris@16
|
61 }
|
Chris@16
|
62 }; // class guard
|
Chris@16
|
63
|
Chris@16
|
64 } // namespace pool
|
Chris@16
|
65 } // namespace details
|
Chris@16
|
66
|
Chris@16
|
67 } // namespace boost
|
Chris@16
|
68
|
Chris@16
|
69 #endif
|