1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 08:58:11 +00:00

LibThreading: Use a condvar to signal the BackgroundAction thread

Now that pthread_cond_t works correctly thanks to Sergey, we can use
them to wake up the BackgroundAction worker thread instead of making
a Unix pipe. :^)
This commit is contained in:
Andreas Kling 2021-07-07 14:23:06 +02:00
parent 5fbb1d9e01
commit fd155193e7

View file

@ -11,43 +11,36 @@
#include <LibThreading/Thread.h> #include <LibThreading/Thread.h>
#include <unistd.h> #include <unistd.h>
static Threading::Lockable<Queue<Function<void()>>>* s_all_actions; static pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t s_condition = PTHREAD_COND_INITIALIZER;
static Queue<Function<void()>>* s_all_actions;
static Threading::Thread* s_background_thread; static Threading::Thread* s_background_thread;
static int s_notify_pipe_fds[2];
static intptr_t background_thread_func() static intptr_t background_thread_func()
{ {
Vector<Function<void()>> actions;
while (true) { while (true) {
char buffer[1];
auto nread = read(s_notify_pipe_fds[0], buffer, sizeof(buffer));
if (nread < 0) {
perror("read");
_exit(1);
}
Vector<Function<void()>> work_items; pthread_mutex_lock(&s_mutex);
{
Threading::Locker locker(s_all_actions->lock());
while (!s_all_actions->resource().is_empty()) { while (s_all_actions->is_empty())
work_items.append(s_all_actions->resource().dequeue()); pthread_cond_wait(&s_condition, &s_mutex);
}
}
for (auto& work_item : work_items) while (!s_all_actions->is_empty())
work_item(); actions.append(s_all_actions->dequeue());
pthread_mutex_unlock(&s_mutex);
for (auto& action : actions)
action();
actions.clear();
} }
VERIFY_NOT_REACHED();
} }
static void init() static void init()
{ {
if (pipe(s_notify_pipe_fds) < 0) { s_all_actions = new Queue<Function<void()>>;
perror("pipe");
_exit(1);
}
s_all_actions = new Threading::Lockable<Queue<Function<void()>>>();
s_background_thread = &Threading::Thread::construct(background_thread_func).leak_ref(); s_background_thread = &Threading::Thread::construct(background_thread_func).leak_ref();
s_background_thread->set_name("Background thread"); s_background_thread->set_name("Background thread");
s_background_thread->start(); s_background_thread->start();
@ -64,11 +57,9 @@ void Threading::BackgroundActionBase::enqueue_work(Function<void()> work)
{ {
if (s_all_actions == nullptr) if (s_all_actions == nullptr)
init(); init();
Locker locker(s_all_actions->lock());
s_all_actions->resource().enqueue(move(work)); pthread_mutex_lock(&s_mutex);
char ch = 'x'; s_all_actions->enqueue(move(work));
if (write(s_notify_pipe_fds[1], &ch, sizeof(ch)) < 0) { pthread_cond_broadcast(&s_condition);
perror("write"); pthread_mutex_unlock(&s_mutex);
_exit(1);
}
} }