2020-01-18 09:38:21 +01:00
|
|
|
/*
|
2020-01-24 16:45:29 +03:00
|
|
|
* Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
|
2020-01-18 09:38:21 +01:00
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-01-18 09:38:21 +01:00
|
|
|
*/
|
|
|
|
|
2020-09-18 09:49:51 +02:00
|
|
|
#include <AK/Queue.h>
|
2021-05-22 18:47:42 +02:00
|
|
|
#include <LibThreading/BackgroundAction.h>
|
|
|
|
#include <LibThreading/Lock.h>
|
|
|
|
#include <LibThreading/Thread.h>
|
2019-08-25 18:55:56 +03:00
|
|
|
|
2021-05-22 18:47:42 +02:00
|
|
|
static Threading::Lockable<Queue<Function<void()>>>* s_all_actions;
|
|
|
|
static Threading::Thread* s_background_thread;
|
2019-08-25 18:55:56 +03:00
|
|
|
|
2021-04-26 19:09:04 +02:00
|
|
|
static intptr_t background_thread_func()
|
2019-08-25 18:55:56 +03:00
|
|
|
{
|
|
|
|
while (true) {
|
|
|
|
Function<void()> work_item;
|
|
|
|
{
|
2021-05-22 18:47:42 +02:00
|
|
|
Threading::Locker locker(s_all_actions->lock());
|
2019-08-25 18:55:56 +03:00
|
|
|
|
|
|
|
if (!s_all_actions->resource().is_empty())
|
|
|
|
work_item = s_all_actions->resource().dequeue();
|
|
|
|
}
|
|
|
|
if (work_item)
|
|
|
|
work_item();
|
|
|
|
else
|
|
|
|
sleep(1);
|
|
|
|
}
|
|
|
|
|
2021-02-23 20:42:32 +01:00
|
|
|
VERIFY_NOT_REACHED();
|
2019-08-25 18:55:56 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
static void init()
|
|
|
|
{
|
2021-05-22 18:47:42 +02:00
|
|
|
s_all_actions = new Threading::Lockable<Queue<Function<void()>>>();
|
|
|
|
s_background_thread = &Threading::Thread::construct(background_thread_func).leak_ref();
|
2019-08-25 18:55:56 +03:00
|
|
|
s_background_thread->set_name("Background thread");
|
|
|
|
s_background_thread->start();
|
|
|
|
}
|
|
|
|
|
2021-05-22 18:47:42 +02:00
|
|
|
Threading::Lockable<Queue<Function<void()>>>& Threading::BackgroundActionBase::all_actions()
|
2019-08-25 18:55:56 +03:00
|
|
|
{
|
|
|
|
if (s_all_actions == nullptr)
|
|
|
|
init();
|
|
|
|
return *s_all_actions;
|
|
|
|
}
|
|
|
|
|
2021-05-22 18:47:42 +02:00
|
|
|
Threading::Thread& Threading::BackgroundActionBase::background_thread()
|
2019-08-25 18:55:56 +03:00
|
|
|
{
|
|
|
|
if (s_background_thread == nullptr)
|
|
|
|
init();
|
|
|
|
return *s_background_thread;
|
|
|
|
}
|