Line data Source code
1 :
2 : /* Copyright (c) 2009-2017, Stefan Eilemann <eile@equalizergraphics.com>
3 : *
4 : * This library is free software; you can redistribute it and/or modify it under
5 : * the terms of the GNU Lesser General Public License version 2.1 as published
6 : * by the Free Software Foundation.
7 : *
8 : * This library is distributed in the hope that it will be useful, but WITHOUT
9 : * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 : * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
11 : * details.
12 : *
13 : * You should have received a copy of the GNU Lesser General Public License
14 : * along with this library; if not, write to the Free Software Foundation, Inc.,
15 : * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16 : */
17 :
18 : #ifndef LUNCHBOX_LOCKABLE_H
19 : #define LUNCHBOX_LOCKABLE_H
20 :
21 : #include <lunchbox/log.h> // used inline
22 :
23 : #include <boost/noncopyable.hpp>
24 : #include <iostream>
25 : #include <mutex>
26 :
27 : namespace lunchbox
28 : {
29 : /**
30 : * A convenience structure to hold data together with a lock for access.
31 : *
32 : * Locking the data still has to be done manually, e.g, using a ScopedMutex.
33 : */
34 : template <class D, class L = std::mutex>
35 25 : class Lockable : public boost::noncopyable
36 : {
37 : public:
38 : /** Construct a new lockable data structure. @version 1.0 */
39 25 : Lockable() {}
40 : /** Construct and initialize a new data structure. @version 1.0 */
41 : explicit Lockable(const D& value)
42 : : data(value)
43 : {
44 : }
45 :
46 : /** Construct and initialize a new data structure. @version 1.3.2 */
47 : template <class P1>
48 : Lockable(const P1& p1)
49 : : data(p1)
50 : {
51 : }
52 :
53 : /** Access the held data. @version 1.0 */
54 3049 : D* operator->() { return &data; }
55 : /** Access the held data. @version 1.0 */
56 : const D* operator->() const { return &data; }
57 : /** Access the held data. @version 1.1.5 */
58 : D& operator*() { return data; }
59 : /** Access the held data. @version 1.1.5 */
60 : const D& operator*() const { return data; }
61 : /** @return true if the data is equal to the rhs object. @version 1.0*/
62 : bool operator==(const D& rhs) const { return (data == rhs); }
63 : /** Assign another value to the data. @version 1.0 */
64 : Lockable& operator=(const D& rhs)
65 : {
66 : data = rhs;
67 : return *this;
68 : }
69 :
70 : D data;
71 : mutable L lock;
72 : };
73 :
74 : /** Print the data to the given output stream. */
75 : template <class D, class L>
76 : inline std::ostream& operator<<(std::ostream& os, const Lockable<D, L>& l)
77 : {
78 : return os << disableFlush << "<" << l.lock.isSet() << " " << l.data << ">"
79 : << enableFlush;
80 : }
81 : }
82 : #endif // LUNCHBOX_LOCKABLE_H
|