aboutsummaryrefslogtreecommitdiff
path: root/lldb/source/Host/common/MainLoopBase.cpp
blob: 64a57e65849e99f654d5abd28b6ec5d753dfb1af (plain)
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
//===-- MainLoopBase.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/MainLoopBase.h"
#include <chrono>

using namespace lldb;
using namespace lldb_private;

void MainLoopBase::AddCallback(const Callback &callback, TimePoint point) {
  bool interrupt_needed;
  {
    std::lock_guard<std::mutex> lock{m_callback_mutex};
    // We need to interrupt the main thread if this callback is scheduled to
    // execute at an earlier time than the earliest callback registered so far.
    interrupt_needed = m_callbacks.empty() || point < m_callbacks.top().first;
    m_callbacks.emplace(point, callback);
  }
  if (interrupt_needed)
    Interrupt();
}

void MainLoopBase::ProcessCallbacks() {
  while (true) {
    Callback callback;
    {
      std::lock_guard<std::mutex> lock{m_callback_mutex};
      if (m_callbacks.empty() ||
          std::chrono::steady_clock::now() < m_callbacks.top().first)
        return;
      callback = std::move(m_callbacks.top().second);
      m_callbacks.pop();
    }

    callback(*this);
  }
}

std::optional<MainLoopBase::TimePoint> MainLoopBase::GetNextWakeupTime() {
  std::lock_guard<std::mutex> lock(m_callback_mutex);
  if (m_callbacks.empty())
    return std::nullopt;
  return m_callbacks.top().first;
}