EventLoop.h 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. /*
  2. * Copyright (c) 2018-2023, 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 WaitMode {
  53. WaitForEvents,
  54. PollForEvents,
  55. };
  56. explicit EventLoop(MakeInspectable = MakeInspectable::No);
  57. ~EventLoop();
  58. static void initialize_wake_pipes();
  59. static bool has_been_instantiated();
  60. // Pump the event loop until its exit is requested.
  61. int exec();
  62. // Process events, generally called by exec() in a loop.
  63. // This should really only be used for integrating with other event loops.
  64. // The wait mode determines whether pump() uses select() to wait for the next event.
  65. size_t pump(WaitMode = WaitMode::WaitForEvents);
  66. // Pump the event loop until some condition is met.
  67. void spin_until(Function<bool()>);
  68. // Post an event to this event loop.
  69. void post_event(Object& receiver, NonnullOwnPtr<Event>&&);
  70. void add_job(NonnullRefPtr<Promise<NonnullRefPtr<Object>>> job_promise);
  71. void deferred_invoke(Function<void()> invokee)
  72. {
  73. auto context = DeferredInvocationContext::construct();
  74. post_event(context, make<Core::DeferredInvocationEvent>(context, move(invokee)));
  75. }
  76. void wake();
  77. void quit(int);
  78. void unquit();
  79. bool was_exit_requested() const { return m_exit_requested; }
  80. // The registration functions act upon the current loop of the current thread.
  81. static int register_timer(Object&, int milliseconds, bool should_reload, TimerShouldFireWhenNotVisible);
  82. static bool unregister_timer(int timer_id);
  83. static void register_notifier(Badge<Notifier>, Notifier&);
  84. static void unregister_notifier(Badge<Notifier>, Notifier&);
  85. static int register_signal(int signo, Function<void(int)> handler);
  86. static void unregister_signal(int handler_id);
  87. // Note: Boost uses Parent/Child/Prepare, but we don't really have anything
  88. // interesting to do in the parent or before forking.
  89. enum class ForkEvent {
  90. Child,
  91. };
  92. static void notify_forked(ForkEvent);
  93. static EventLoop& current();
  94. private:
  95. void wait_for_event(WaitMode);
  96. Optional<Time> get_next_timer_expiration();
  97. static void dispatch_signal(int);
  98. static void handle_signal(int);
  99. static pid_t s_pid;
  100. bool m_exit_requested { false };
  101. int m_exit_code { 0 };
  102. static thread_local int s_wake_pipe_fds[2];
  103. static thread_local bool s_wake_pipe_initialized;
  104. // The wake pipe of this event loop needs to be accessible from other threads.
  105. int (*m_wake_pipe_fds)[2];
  106. struct Private;
  107. NonnullOwnPtr<Private> m_private;
  108. };
  109. inline void deferred_invoke(Function<void()> invokee)
  110. {
  111. EventLoop::current().deferred_invoke(move(invokee));
  112. }
  113. }