Overte C++ Documentation
ThreadSafeValueCache.h
1 //
2 // ThreadSafeValueCache.h
3 // interface/src/avatar
4 //
5 // Copyright 2012 High Fidelity, Inc.
6 //
7 // Distributed under the Apache License, Version 2.0.
8 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
9 //
10 
11 #ifndef hifi_ThreadSafeValueCache_h
12 #define hifi_ThreadSafeValueCache_h
13 
14 #include <mutex>
15 
16 // Helper class for for sharing a value type between threads.
17 // It allows many threads to get or set a value atomically.
18 // This provides cache semantics, any get will return the last set value.
19 //
20 // For example: This can be used to copy values between C++ code running on the application thread
21 // and JavaScript which is running on a different thread.
22 
23 template <typename T>
24 class ThreadSafeValueCache {
25 public:
26  ThreadSafeValueCache() {}
27  ThreadSafeValueCache(const T& v) : _value { v } {}
28 
29  // returns atomic copy of the cached value.
30  T get() const {
31  std::lock_guard<std::mutex> guard(_mutex);
32  return _value;
33  }
34 
35  // returns atomic copy of the cached value and indicates validity
36  T get(bool& valid) const {
37  std::lock_guard<std::mutex> guard(_mutex);
38  valid = _valid;
39  return _value;
40  }
41 
42  // will reflect copy of value into the cache.
43  void set(const T& v) {
44  std::lock_guard<std::mutex> guard(_mutex);
45  _value = v;
46  _valid = true;
47  }
48 
49  // indicate that the value is not longer valid
50  void invalidate() {
51  std::lock_guard<std::mutex> guard(_mutex);
52  _valid = false;
53  }
54 
55  bool isValid() const {
56  std::lock_guard<std::mutex> guard(_mutex);
57  return _valid;
58  }
59 
60 private:
61  mutable std::mutex _mutex;
62  T _value;
63  bool _valid { false };
64 
65  // no copies
66  ThreadSafeValueCache(const ThreadSafeValueCache&) = delete;
67  ThreadSafeValueCache& operator=(const ThreadSafeValueCache&) = delete;
68 };
69 
70 #endif // #define hifi_ThreadSafeValueCache_h