Predicate.h revision 360784
1//===-- Predicate.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 liblldb_Predicate_h_
10#define liblldb_Predicate_h_
11
12#include <stdint.h>
13#include <time.h>
14
15#include <condition_variable>
16#include <mutex>
17
18#include "lldb/Utility/Timeout.h"
19#include "lldb/lldb-defines.h"
20
21//#define DB_PTHREAD_LOG_EVENTS
22
23/// Enumerations for broadcasting.
24namespace lldb_private {
25
26enum PredicateBroadcastType {
27  eBroadcastNever,   ///< No broadcast will be sent when the value is modified.
28  eBroadcastAlways,  ///< Always send a broadcast when the value is modified.
29  eBroadcastOnChange ///< Only broadcast if the value changes when the value is
30                     /// modified.
31};
32
33/// \class Predicate Predicate.h "lldb/Utility/Predicate.h"
34/// A C++ wrapper class for providing threaded access to a value of
35/// type T.
36///
37/// A templatized class that provides multi-threaded access to a value
38/// of type T. Threads can efficiently wait for bits within T to be set
39/// or reset, or wait for T to be set to be equal/not equal to a
40/// specified values.
41template <class T> class Predicate {
42public:
43  /// Default constructor.
44  ///
45  /// Initializes the mutex, condition and value with their default
46  /// constructors.
47  Predicate() : m_value(), m_mutex(), m_condition() {}
48
49  /// Construct with initial T value \a initial_value.
50  ///
51  /// Initializes the mutex and condition with their default
52  /// constructors, and initializes the value with \a initial_value.
53  ///
54  /// \param[in] initial_value
55  ///     The initial value for our T object.
56  Predicate(T initial_value)
57      : m_value(initial_value), m_mutex(), m_condition() {}
58
59  /// Destructor.
60  ///
61  /// Destroy the condition, mutex, and T objects.
62  ~Predicate() = default;
63
64  /// Value get accessor.
65  ///
66  /// Copies the current \a m_value in a thread safe manor and returns
67  /// the copied value.
68  ///
69  /// \return
70  ///     A copy of the current value.
71  T GetValue() const {
72    std::lock_guard<std::mutex> guard(m_mutex);
73    T value = m_value;
74    return value;
75  }
76
77  /// Value set accessor.
78  ///
79  /// Set the contained \a m_value to \a new_value in a thread safe
80  /// way and broadcast if needed.
81  ///
82  /// \param[in] value
83  ///     The new value to set.
84  ///
85  /// \param[in] broadcast_type
86  ///     A value indicating when and if to broadcast. See the
87  ///     PredicateBroadcastType enumeration for details.
88  ///
89  /// \see Predicate::Broadcast()
90  void SetValue(T value, PredicateBroadcastType broadcast_type) {
91    std::lock_guard<std::mutex> guard(m_mutex);
92#ifdef DB_PTHREAD_LOG_EVENTS
93    printf("%s (value = 0x%8.8x, broadcast_type = %i)\n", __FUNCTION__, value,
94           broadcast_type);
95#endif
96    const T old_value = m_value;
97    m_value = value;
98
99    Broadcast(old_value, broadcast_type);
100  }
101
102  /// Wait for Cond(m_value) to be true.
103  ///
104  /// Waits in a thread safe way for Cond(m_value) to be true. If Cond(m_value)
105  /// is already true, this function will return without waiting.
106  ///
107  /// It is possible for the value to be changed between the time the value is
108  /// set and the time the waiting thread wakes up. If the value no longer
109  /// satisfies the condition when the waiting thread wakes up, it will go back
110  /// into a wait state. It may be necessary for the calling code to use
111  /// additional thread synchronization methods to detect transitory states.
112  ///
113  /// \param[in] Cond
114  ///     The condition we want \a m_value satisfy.
115  ///
116  /// \param[in] timeout
117  ///     How long to wait for the condition to hold.
118  ///
119  /// \return
120  ///     m_value if Cond(m_value) is true, None otherwise (timeout occurred).
121  template <typename C>
122  llvm::Optional<T> WaitFor(C Cond, const Timeout<std::micro> &timeout) {
123    std::unique_lock<std::mutex> lock(m_mutex);
124    auto RealCond = [&] { return Cond(m_value); };
125    if (!timeout) {
126      m_condition.wait(lock, RealCond);
127      return m_value;
128    }
129    if (m_condition.wait_for(lock, *timeout, RealCond))
130      return m_value;
131    return llvm::None;
132  }
133  /// Wait for \a m_value to be equal to \a value.
134  ///
135  /// Waits in a thread safe way for \a m_value to be equal to \a
136  /// value. If \a m_value is already equal to \a value, this
137  /// function will return without waiting.
138  ///
139  /// It is possible for the value to be changed between the time
140  /// the value is set and the time the waiting thread wakes up.
141  /// If the value no longer matches the requested value when the
142  /// waiting thread wakes up, it will go back into a wait state.  It
143  /// may be necessary for the calling code to use additional thread
144  /// synchronization methods to detect transitory states.
145  ///
146  /// \param[in] value
147  ///     The value we want \a m_value to be equal to.
148  ///
149  /// \param[in] timeout
150  ///     How long to wait for the condition to hold.
151  ///
152  /// \return
153  ///     true if the \a m_value is equal to \a value, false otherwise (timeout
154  ///     occurred).
155  bool WaitForValueEqualTo(T value,
156                           const Timeout<std::micro> &timeout = llvm::None) {
157    return WaitFor([&value](T current) { return value == current; }, timeout) !=
158           llvm::None;
159  }
160
161  /// Wait for \a m_value to not be equal to \a value.
162  ///
163  /// Waits in a thread safe way for \a m_value to not be equal to \a
164  /// value. If \a m_value is already not equal to \a value, this
165  /// function will return without waiting.
166  ///
167  /// It is possible for the value to be changed between the time
168  /// the value is set and the time the waiting thread wakes up.
169  /// If the value is equal to the test value when the waiting thread
170  /// wakes up, it will go back into a wait state.  It may be
171  /// necessary for the calling code to use additional thread
172  /// synchronization methods to detect transitory states.
173  ///
174  /// \param[in] value
175  ///     The value we want \a m_value to not be equal to.
176  ///
177  /// \param[in] timeout
178  ///     How long to wait for the condition to hold.
179  ///
180  /// \return
181  ///     m_value if m_value != value, None otherwise (timeout occurred).
182  llvm::Optional<T>
183  WaitForValueNotEqualTo(T value,
184                         const Timeout<std::micro> &timeout = llvm::None) {
185    return WaitFor([&value](T current) { return value != current; }, timeout);
186  }
187
188protected:
189  // pthread condition and mutex variable to control access and allow blocking
190  // between the main thread and the spotlight index thread.
191  T m_value; ///< The templatized value T that we are protecting access to
192  mutable std::mutex m_mutex; ///< The mutex to use when accessing the data
193  std::condition_variable m_condition; ///< The pthread condition variable to
194                                       /// use for signaling that data available
195                                       /// or changed.
196
197private:
198  /// Broadcast if needed.
199  ///
200  /// Check to see if we need to broadcast to our condition variable
201  /// depending on the \a old_value and on the \a broadcast_type.
202  ///
203  /// If \a broadcast_type is eBroadcastNever, no broadcast will be
204  /// sent.
205  ///
206  /// If \a broadcast_type is eBroadcastAlways, the condition variable
207  /// will always be broadcast.
208  ///
209  /// If \a broadcast_type is eBroadcastOnChange, the condition
210  /// variable be broadcast if the owned value changes.
211  void Broadcast(T old_value, PredicateBroadcastType broadcast_type) {
212    bool broadcast =
213        (broadcast_type == eBroadcastAlways) ||
214        ((broadcast_type == eBroadcastOnChange) && old_value != m_value);
215#ifdef DB_PTHREAD_LOG_EVENTS
216    printf("%s (old_value = 0x%8.8x, broadcast_type = %i) m_value = 0x%8.8x, "
217           "broadcast = %u\n",
218           __FUNCTION__, old_value, broadcast_type, m_value, broadcast);
219#endif
220    if (broadcast)
221      m_condition.notify_all();
222  }
223
224  DISALLOW_COPY_AND_ASSIGN(Predicate);
225};
226
227} // namespace lldb_private
228
229#endif // liblldb_Predicate_h_
230