xref: /llvm-project/lldb/source/Host/common/MainLoopBase.cpp (revision 55068dc3b7725f24de82dd4510162865c91a4f5e)
1 //===-- MainLoopBase.cpp --------------------------------------------------===//
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 #include "lldb/Host/MainLoopBase.h"
10 #include <chrono>
11 
12 using namespace lldb;
13 using namespace lldb_private;
14 
15 void MainLoopBase::AddCallback(const Callback &callback, TimePoint point) {
16   bool interrupt_needed;
17   {
18     std::lock_guard<std::mutex> lock{m_callback_mutex};
19     // We need to interrupt the main thread if this callback is scheduled to
20     // execute at an earlier time than the earliest callback registered so far.
21     interrupt_needed = m_callbacks.empty() || point < m_callbacks.top().first;
22     m_callbacks.emplace(point, callback);
23   }
24   if (interrupt_needed)
25     Interrupt();
26 }
27 
28 void MainLoopBase::ProcessCallbacks() {
29   while (true) {
30     Callback callback;
31     {
32       std::lock_guard<std::mutex> lock{m_callback_mutex};
33       if (m_callbacks.empty() ||
34           std::chrono::steady_clock::now() < m_callbacks.top().first)
35         return;
36       callback = std::move(m_callbacks.top().second);
37       m_callbacks.pop();
38     }
39 
40     callback(*this);
41   }
42 }
43 
44 std::optional<MainLoopBase::TimePoint> MainLoopBase::GetNextWakeupTime() {
45   std::lock_guard<std::mutex> lock(m_callback_mutex);
46   if (m_callbacks.empty())
47     return std::nullopt;
48   return m_callbacks.top().first;
49 }
50