1 //===-- ThreadSafeValue.h ---------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifndef liblldb_ThreadSafeValue_h_ 11 #define liblldb_ThreadSafeValue_h_ 12 13 14 #include <mutex> 15 16 #include "lldb/lldb-defines.h" 17 18 namespace lldb_private { 19 20 template <class T> class ThreadSafeValue { 21 public: 22 //------------------------------------------------------------------ 23 // Constructors and Destructors 24 //------------------------------------------------------------------ ThreadSafeValue()25 ThreadSafeValue() : m_value(), m_mutex() {} 26 ThreadSafeValue(const T & value)27 ThreadSafeValue(const T &value) : m_value(value), m_mutex() {} 28 ~ThreadSafeValue()29 ~ThreadSafeValue() {} 30 GetValue()31 T GetValue() const { 32 T value; 33 { 34 std::lock_guard<std::recursive_mutex> guard(m_mutex); 35 value = m_value; 36 } 37 return value; 38 } 39 40 // Call this if you have already manually locked the mutex using the 41 // GetMutex() accessor GetValueNoLock()42 const T &GetValueNoLock() const { return m_value; } 43 SetValue(const T & value)44 void SetValue(const T &value) { 45 std::lock_guard<std::recursive_mutex> guard(m_mutex); 46 m_value = value; 47 } 48 49 // Call this if you have already manually locked the mutex using the 50 // GetMutex() accessor SetValueNoLock(const T & value)51 void SetValueNoLock(const T &value) { m_value = value; } 52 GetMutex()53 std::recursive_mutex &GetMutex() { return m_mutex; } 54 55 private: 56 T m_value; 57 mutable std::recursive_mutex m_mutex; 58 59 //------------------------------------------------------------------ 60 // For ThreadSafeValue only 61 //------------------------------------------------------------------ 62 DISALLOW_COPY_AND_ASSIGN(ThreadSafeValue); 63 }; 64 65 } // namespace lldb_private 66 #endif // liblldb_ThreadSafeValue_h_ 67