1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 00:17:46 +00:00

LibCore: Allow EventLoops to run on multiple threads safely

The event loop system was previously very singletony to the point that
there's only a single event loop stack per process and only one event
loop (the topmost) can run at a time. This commit simply makes the event
loop stack and related structures thread-local so that each thread has
an isolated event loop system.

Some things are kept at a global level and synchronized with the new
MutexProtected: The main event loop needs to still be obtainable from
anywhere, as it closes down the application when it exits. The ID
allocator is global as IDs should not be shared even between threads.
And for the inspector server connection, the same as for the main loop
holds.

Note that currently, the wake pipe is only created by the main thread,
so notifications don't work on other threads.

This removes the temporary mutex fix for notifiers, introduced in
0631d3fed5 .
This commit is contained in:
kleines Filmröllchen 2022-01-02 14:52:38 +01:00 committed by Andreas Kling
parent 3d6e08156d
commit 69c1910037
4 changed files with 80 additions and 61 deletions

View file

@ -1,5 +1,6 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2022, kleines Filmröllchen <malu.bertsch@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@ -18,11 +19,14 @@
#include <LibCore/DeferredInvocationContext.h>
#include <LibCore/Event.h>
#include <LibCore/Forward.h>
#include <LibThreading/MutexProtected.h>
#include <sys/time.h>
#include <sys/types.h>
namespace Core {
static Threading::MutexProtected<EventLoop*> s_main_event_loop;
class EventLoop {
public:
enum class MakeInspectable {
@ -48,7 +52,14 @@ public:
void post_event(Object& receiver, NonnullOwnPtr<Event>&&);
static EventLoop& main();
template<typename Callback>
static decltype(auto) with_main_locked(Callback callback)
{
return s_main_event_loop.with_locked([&callback](auto*& event_loop) {
VERIFY(event_loop != nullptr);
return callback(event_loop);
});
}
static EventLoop& current();
bool was_exit_requested() const { return m_exit_requested; }
@ -111,7 +122,7 @@ private:
bool m_exit_requested { false };
int m_exit_code { 0 };
static int s_wake_pipe_fds[2];
static thread_local int s_wake_pipe_fds[2];
struct Private;
NonnullOwnPtr<Private> m_private;