1 //===-- ProcessRunLock.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_ProcessRunLock_h_
11 #define liblldb_ProcessRunLock_h_
12 
13 // C Includes
14 #include <stdint.h>
15 #include <time.h>
16 
17 // C++ Includes
18 // Other libraries and framework includes
19 // Project includes
20 #include "lldb/lldb-defines.h"
21 #include "lldb/Host/Condition.h"
22 
23 //----------------------------------------------------------------------
24 /// Enumerations for broadcasting.
25 //----------------------------------------------------------------------
26 namespace lldb_private {
27 
28 //----------------------------------------------------------------------
29 /// @class ProcessRunLock ProcessRunLock.h "lldb/Host/ProcessRunLock.h"
30 /// @brief A class used to prevent the process from starting while other
31 /// threads are accessing its data, and prevent access to its data while
32 /// it is running.
33 //----------------------------------------------------------------------
34 
35 class ProcessRunLock
36 {
37 public:
38     ProcessRunLock();
39     ~ProcessRunLock();
40 
41     bool ReadTryLock ();
42     bool ReadUnlock ();
43     bool SetRunning ();
44     bool TrySetRunning ();
45     bool SetStopped ();
46 
47     class ProcessRunLocker
48     {
49     public:
50         ProcessRunLocker () :
51             m_lock (nullptr)
52         {
53         }
54 
55         ~ProcessRunLocker()
56         {
57             Unlock();
58         }
59 
60         // Try to lock the read lock, but only do so if there are no writers.
61         bool
62         TryLock (ProcessRunLock *lock)
63         {
64             if (m_lock)
65             {
66                 if (m_lock == lock)
67                     return true; // We already have this lock locked
68                 else
69                     Unlock();
70             }
71             if (lock)
72             {
73                 if (lock->ReadTryLock())
74                 {
75                     m_lock = lock;
76                     return true;
77                 }
78             }
79             return false;
80         }
81 
82     protected:
83         void
84         Unlock ()
85         {
86             if (m_lock)
87             {
88                 m_lock->ReadUnlock();
89                 m_lock = nullptr;
90             }
91         }
92 
93         ProcessRunLock *m_lock;
94 
95     private:
96         DISALLOW_COPY_AND_ASSIGN(ProcessRunLocker);
97     };
98 
99 protected:
100     lldb::rwlock_t m_rwlock;
101     bool m_running;
102 
103 private:
104     DISALLOW_COPY_AND_ASSIGN(ProcessRunLock);
105 };
106 
107 } // namespace lldb_private
108 
109 #endif // liblldb_ProcessRunLock_h_
110