1 //===-- ThreadSafeValue.h ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLDB_CORE_THREADSAFEVALUE_H
10 #define LLDB_CORE_THREADSAFEVALUE_H
11 
12 #include <mutex>
13 
14 #include "lldb/lldb-defines.h"
15 
16 namespace lldb_private {
17 
18 template <class T> class ThreadSafeValue {
19 public:
20   // Constructors and Destructors
21   ThreadSafeValue() : m_value(), m_mutex() {}
22 
23   ThreadSafeValue(const T &value) : m_value(value), m_mutex() {}
24 
25   ~ThreadSafeValue() {}
26 
27   T GetValue() const {
28     T value;
29     {
30       std::lock_guard<std::recursive_mutex> guard(m_mutex);
31       value = m_value;
32     }
33     return value;
34   }
35 
36   // Call this if you have already manually locked the mutex using the
37   // GetMutex() accessor
38   const T &GetValueNoLock() const { return m_value; }
39 
40   void SetValue(const T &value) {
41     std::lock_guard<std::recursive_mutex> guard(m_mutex);
42     m_value = value;
43   }
44 
45   // Call this if you have already manually locked the mutex using the
46   // GetMutex() accessor
47   void SetValueNoLock(const T &value) { m_value = value; }
48 
49   std::recursive_mutex &GetMutex() { return m_mutex; }
50 
51 private:
52   T m_value;
53   mutable std::recursive_mutex m_mutex;
54 
55   // For ThreadSafeValue only
56   ThreadSafeValue(const ThreadSafeValue &) = delete;
57   const ThreadSafeValue &operator=(const ThreadSafeValue &) = delete;
58 };
59 
60 } // namespace lldb_private
61 #endif // LLDB_CORE_THREADSAFEVALUE_H
62