File: Alarm.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (222 lines) | stat: -rw-r--r-- 7,114 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
//===-- Alarm.cpp ---------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/Alarm.h"
#include "lldb/Host/ThreadLauncher.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"

using namespace lldb;
using namespace lldb_private;

Alarm::Alarm(Duration timeout, bool run_callback_on_exit)
    : m_timeout(timeout), m_run_callbacks_on_exit(run_callback_on_exit) {
  StartAlarmThread();
}

Alarm::~Alarm() { StopAlarmThread(); }

Alarm::Handle Alarm::Create(std::function<void()> callback) {
  // Gracefully deal with the unlikely event that the alarm thread failed to
  // launch.
  if (!AlarmThreadRunning())
    return INVALID_HANDLE;

  // Compute the next expiration before we take the lock. This ensures that
  // waiting on the lock doesn't eat into the timeout.
  const TimePoint expiration = GetNextExpiration();

  Handle handle = INVALID_HANDLE;

  {
    std::lock_guard<std::mutex> alarm_guard(m_alarm_mutex);

    // Create a new unique entry and remember its handle.
    m_entries.emplace_back(callback, expiration);
    handle = m_entries.back().handle;

    // Tell the alarm thread we need to recompute the next alarm.
    m_recompute_next_alarm = true;
  }

  m_alarm_cv.notify_one();
  return handle;
}

bool Alarm::Restart(Handle handle) {
  // Gracefully deal with the unlikely event that the alarm thread failed to
  // launch.
  if (!AlarmThreadRunning())
    return false;

  // Compute the next expiration before we take the lock. This ensures that
  // waiting on the lock doesn't eat into the timeout.
  const TimePoint expiration = GetNextExpiration();

  {
    std::lock_guard<std::mutex> alarm_guard(m_alarm_mutex);

    // Find the entry corresponding to the given handle.
    const auto it =
        std::find_if(m_entries.begin(), m_entries.end(),
                     [handle](Entry &entry) { return entry.handle == handle; });
    if (it == m_entries.end())
      return false;

    // Update the expiration.
    it->expiration = expiration;

    // Tell the alarm thread we need to recompute the next alarm.
    m_recompute_next_alarm = true;
  }

  m_alarm_cv.notify_one();
  return true;
}

bool Alarm::Cancel(Handle handle) {
  // Gracefully deal with the unlikely event that the alarm thread failed to
  // launch.
  if (!AlarmThreadRunning())
    return false;

  {
    std::lock_guard<std::mutex> alarm_guard(m_alarm_mutex);

    const auto it =
        std::find_if(m_entries.begin(), m_entries.end(),
                     [handle](Entry &entry) { return entry.handle == handle; });

    if (it == m_entries.end())
      return false;

    m_entries.erase(it);
  }

  // No need to notify the alarm thread. This only affects the alarm thread if
  // we removed the entry that corresponds to the next alarm. If that's the
  // case, the thread will wake up as scheduled, find no expired events, and
  // recompute the next alarm time.
  return true;
}

Alarm::Entry::Entry(Alarm::Callback callback, Alarm::TimePoint expiration)
    : handle(Alarm::GetNextUniqueHandle()), callback(std::move(callback)),
      expiration(std::move(expiration)) {}

void Alarm::StartAlarmThread() {
  if (!m_alarm_thread.IsJoinable()) {
    llvm::Expected<HostThread> alarm_thread = ThreadLauncher::LaunchThread(
        "lldb.debugger.alarm-thread", [this] { return AlarmThread(); },
        8 * 1024 * 1024); // Use larger 8MB stack for this thread
    if (alarm_thread) {
      m_alarm_thread = *alarm_thread;
    } else {
      LLDB_LOG_ERROR(GetLog(LLDBLog::Host), alarm_thread.takeError(),
                     "failed to launch host thread: {0}");
    }
  }
}

void Alarm::StopAlarmThread() {
  if (m_alarm_thread.IsJoinable()) {
    {
      std::lock_guard<std::mutex> alarm_guard(m_alarm_mutex);
      m_exit = true;
    }
    m_alarm_cv.notify_one();
    m_alarm_thread.Join(nullptr);
  }
}

bool Alarm::AlarmThreadRunning() { return m_alarm_thread.IsJoinable(); }

lldb::thread_result_t Alarm::AlarmThread() {
  bool exit = false;
  std::optional<TimePoint> next_alarm;

  const auto predicate = [this] { return m_exit || m_recompute_next_alarm; };

  while (!exit) {
    // Synchronization between the main thread and the alarm thread using a
    // mutex and condition variable. There are 2 reasons the thread can wake up:
    //
    // 1. The timeout for the next alarm expired.
    //
    // 2. The condition variable is notified that one of our shared variables
    //    (see predicate) was modified. Either the thread is asked to shut down
    //    or a new alarm came in and we need to recompute the next timeout.
    //
    // Below we only deal with the timeout expiring and fall through for dealing
    // with the rest.
    llvm::SmallVector<Callback, 1> callbacks;
    {
      std::unique_lock<std::mutex> alarm_lock(m_alarm_mutex);
      if (next_alarm) {
        if (!m_alarm_cv.wait_until(alarm_lock, *next_alarm, predicate)) {
          // The timeout for the next alarm expired.

          // Clear the next timeout to signal that we need to recompute the next
          // timeout.
          next_alarm.reset();

          // Iterate over all the callbacks. Call the ones that have expired
          // and remove them from the list.
          const TimePoint now = std::chrono::system_clock::now();
          auto it = m_entries.begin();
          while (it != m_entries.end()) {
            if (it->expiration <= now) {
              callbacks.emplace_back(std::move(it->callback));
              it = m_entries.erase(it);
            } else {
              it++;
            }
          }
        }
      } else {
        m_alarm_cv.wait(alarm_lock, predicate);
      }

      // Fall through after waiting on the condition variable. At this point
      // either the predicate is true or we woke up because an alarm expired.

      // The alarm thread is shutting down.
      if (m_exit) {
        exit = true;
        if (m_run_callbacks_on_exit) {
          for (Entry &entry : m_entries)
            callbacks.emplace_back(std::move(entry.callback));
        }
      }

      // A new alarm was added or an alarm expired. Either way we need to
      // recompute when this thread should wake up for the next alarm.
      if (m_recompute_next_alarm || !next_alarm) {
        for (Entry &entry : m_entries) {
          if (!next_alarm || entry.expiration < *next_alarm)
            next_alarm = entry.expiration;
        }
        m_recompute_next_alarm = false;
      }
    }

    // Outside the lock, call the callbacks.
    for (Callback &callback : callbacks)
      callback();
  }
  return {};
}

Alarm::TimePoint Alarm::GetNextExpiration() const {
  return std::chrono::system_clock::now() + m_timeout;
}

Alarm::Handle Alarm::GetNextUniqueHandle() {
  static std::atomic<Handle> g_next_handle = 1;
  return g_next_handle++;
}