DIY 3.0 data-parallel out-of-core C++ library

- Main Page
- Modules
- Namespaces
- Classes
- Files
- Examples

- File List

All Classes Namespaces Functions Typedefs Groups Pages
critical-resource.hpp
1 #ifndef DIY_CRITICAL_RESOURCE_HPP
2 #define DIY_CRITICAL_RESOURCE_HPP
3
4 namespace diy
5 {
6 // TODO: when not running under C++11, i.e., when lock_guard is TinyThread's
7 // lock_guard, and not C++11's unique_lock, this implementation might
8 // be buggy since the copy constructor is invoked when
9 // critical_resource::access() returns an instance of this class. Once
10 // the temporary is destroyed the mutex is unlocked. I'm not 100%
11 // certain of this because I'd expect a deadlock on copy constructor,
12 // but it's clearly not happening -- so I may be missing something.
13 // (This issue will take care of itself in DIY3 once we switch to C++11 completely.)
14 template<class T, class Mutex>
15 class resource_accessor
16 {
17 public:
18 resource_accessor(T& x, Mutex& m):
19 x_(x), lock_(m) {}
20
21 T& operator*() { return x_; }
22 T* operator->() { return &x_; }
23 const T& operator*() const { return x_; }
24 const T* operator->() const { return &x_; }
25
26 private:
27 T& x_;
28 lock_guard<Mutex> lock_;
29 };
30
31 template<class T, class Mutex = fast_mutex>
32 class critical_resource
33 {
34 public:
35 typedef resource_accessor<T, Mutex> accessor;
36 typedef resource_accessor<const T, Mutex> const_accessor; // eventually, try shared locking
37
38 public:
39 critical_resource() {}
40 critical_resource(const T& x):
41 x_(x) {}
42
43 accessor access() { return accessor(x_, m_); }
44 const_accessor const_access() const { return const_accessor(x_, m_); }
45
46 private:
47 T x_;
48 mutable Mutex m_;
49 };
50 }
51
52
53 #endif
diy::resource_accessor
Definition: critical-resource.hpp:15
diy::lock_guard< Mutex >
diy::critical_resource
Definition: critical-resource.hpp:32