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