EventLoop.h 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, kleines Filmröllchen <filmroellchen@serenityos.org>
  4. * Copyright (c) 2022, the SerenityOS developers.
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #pragma once
  9. #include <AK/Forward.h>
  10. #include <AK/Function.h>
  11. #include <AK/HashMap.h>
  12. #include <AK/Noncopyable.h>
  13. #include <AK/NonnullOwnPtr.h>
  14. #include <AK/NonnullRefPtr.h>
  15. #include <AK/Time.h>
  16. #include <AK/Vector.h>
  17. #include <AK/WeakPtr.h>
  18. #include <LibCore/DeferredInvocationContext.h>
  19. #include <LibCore/Event.h>
  20. #include <LibCore/Forward.h>
  21. #include <LibThreading/MutexProtected.h>
  22. #include <sys/time.h>
  23. #include <sys/types.h>
  24. namespace Core {
  25. // The event loop enables asynchronous (not parallel or multi-threaded) computing by efficiently handling events from various sources.
  26. // Event loops are most important for GUI programs, where the various GUI updates and action callbacks run on the EventLoop,
  27. // as well as services, where asynchronous remote procedure calls of multiple clients are handled.
  28. // Event loops, through select(), allow programs to "go to sleep" for most of their runtime until some event happens.
  29. // EventLoop is too expensive to use in realtime scenarios (read: audio) where even the time required by a single select() system call is too large and unpredictable.
  30. //
  31. // There is at most one running event loop per thread.
  32. // Another event loop can be started while another event loop is already running; that new event loop will take over for the other event loop.
  33. // This is mainly used in LibGUI, where each modal window stacks another event loop until it is closed.
  34. // However, that means you need to be careful with storing the current event loop, as it might already be gone at the time of use.
  35. // Event loops currently handle these kinds of events:
  36. // - Deferred invocations caused by various objects. These are just a generic way of telling the EventLoop to run some function as soon as possible at a later point.
  37. // - Timers, which repeatedly (or once after a delay) run a function on the EventLoop. Note that timers are not super accurate.
  38. // - Filesystem notifications, i.e. whenever a file is read from, written to, etc.
  39. // - POSIX signals, which allow the event loop to act as a signal handler and dispatch those signals in a more user-friendly way.
  40. // - Fork events, because the child process event loop needs to clear its events and handlers.
  41. // - Quit events, i.e. the event loop should exit.
  42. // Any event that the event loop needs to wait on or needs to repeatedly handle is stored in a handle, e.g. s_timers.
  43. //
  44. // EventLoop has one final responsibility: Handling the InspectorServer connection and processing requests to the Object hierarchy.
  45. class EventLoop {
  46. friend struct EventLoopPusher;
  47. public:
  48. enum class MakeInspectable {
  49. No,
  50. Yes,
  51. };
  52. enum class ShouldWake {
  53. No,
  54. Yes
  55. };
  56. enum class WaitMode {
  57. WaitForEvents,
  58. PollForEvents,
  59. };
  60. explicit EventLoop(MakeInspectable = MakeInspectable::No);
  61. ~EventLoop();
  62. static void initialize_wake_pipes();
  63. static bool has_been_instantiated();
  64. // Pump the event loop until its exit is requested.
  65. int exec();
  66. // Process events, generally called by exec() in a loop.
  67. // This should really only be used for integrating with other event loops.
  68. // The wait mode determines whether pump() uses select() to wait for the next event.
  69. size_t pump(WaitMode = WaitMode::WaitForEvents);
  70. // Pump the event loop until some condition is met.
  71. void spin_until(Function<bool()>);
  72. // Post an event to this event loop and possibly wake the loop.
  73. void post_event(Object& receiver, NonnullOwnPtr<Event>&&, ShouldWake = ShouldWake::No);
  74. void wake_once(Object& receiver, int custom_event_type);
  75. void add_job(NonnullRefPtr<Promise<NonnullRefPtr<Object>>> job_promise);
  76. void deferred_invoke(Function<void()> invokee)
  77. {
  78. auto context = DeferredInvocationContext::construct();
  79. post_event(context, make<Core::DeferredInvocationEvent>(context, move(invokee)));
  80. }
  81. void wake();
  82. void quit(int);
  83. void unquit();
  84. bool was_exit_requested() const { return m_exit_requested; }
  85. // The registration functions act upon the current loop of the current thread.
  86. static int register_timer(Object&, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible);
  87. static bool unregister_timer(int timer_id);
  88. static void register_notifier(Badge<Notifier>, Notifier&);
  89. static void unregister_notifier(Badge<Notifier>, Notifier&);
  90. static int register_signal(int signo, Function<void(int)> handler);
  91. static void unregister_signal(int handler_id);
  92. // Note: Boost uses Parent/Child/Prepare, but we don't really have anything
  93. // interesting to do in the parent or before forking.
  94. enum class ForkEvent {
  95. Child,
  96. };
  97. static void notify_forked(ForkEvent);
  98. void take_pending_events_from(EventLoop& other)
  99. {
  100. m_queued_events.extend(move(other.m_queued_events));
  101. }
  102. static EventLoop& current();
  103. static void wake_current();
  104. private:
  105. void wait_for_event(WaitMode);
  106. Optional<Time> get_next_timer_expiration();
  107. static void dispatch_signal(int);
  108. static void handle_signal(int);
  109. struct QueuedEvent {
  110. AK_MAKE_NONCOPYABLE(QueuedEvent);
  111. public:
  112. QueuedEvent(Object& receiver, NonnullOwnPtr<Event>);
  113. QueuedEvent(QueuedEvent&&);
  114. ~QueuedEvent() = default;
  115. WeakPtr<Object> receiver;
  116. NonnullOwnPtr<Event> event;
  117. };
  118. Vector<QueuedEvent, 64> m_queued_events;
  119. Vector<NonnullRefPtr<Promise<NonnullRefPtr<Object>>>> m_pending_promises;
  120. static pid_t s_pid;
  121. bool m_exit_requested { false };
  122. int m_exit_code { 0 };
  123. static thread_local int s_wake_pipe_fds[2];
  124. static thread_local bool s_wake_pipe_initialized;
  125. // The wake pipe of this event loop needs to be accessible from other threads.
  126. int (*m_wake_pipe_fds)[2];
  127. struct Private;
  128. NonnullOwnPtr<Private> m_private;
  129. };
  130. inline void deferred_invoke(Function<void()> invokee)
  131. {
  132. EventLoop::current().deferred_invoke(move(invokee));
  133. }
  134. }