2020-01-18 08:38:21 +00:00
|
|
|
/*
|
2020-01-24 13:45:29 +00:00
|
|
|
* Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
|
2020-01-18 08:38:21 +00:00
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-01-18 08:38:21 +00:00
|
|
|
*/
|
|
|
|
|
2020-09-18 07:49:51 +00:00
|
|
|
#include <AK/Queue.h>
|
2019-08-25 15:55:56 +00:00
|
|
|
#include <LibThread/BackgroundAction.h>
|
2019-08-25 20:51:27 +00:00
|
|
|
#include <LibThread/Lock.h>
|
2020-09-18 07:49:51 +00:00
|
|
|
#include <LibThread/Thread.h>
|
2019-08-25 15:55:56 +00:00
|
|
|
|
2019-08-25 20:51:27 +00:00
|
|
|
static LibThread::Lockable<Queue<Function<void()>>>* s_all_actions;
|
2019-08-25 15:55:56 +00:00
|
|
|
static LibThread::Thread* s_background_thread;
|
|
|
|
|
|
|
|
static int background_thread_func()
|
|
|
|
{
|
|
|
|
while (true) {
|
|
|
|
Function<void()> work_item;
|
|
|
|
{
|
|
|
|
LOCKER(s_all_actions->lock());
|
|
|
|
|
|
|
|
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 19:42:32 +00:00
|
|
|
VERIFY_NOT_REACHED();
|
2019-08-25 15:55:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
static void init()
|
|
|
|
{
|
2019-08-25 20:51:27 +00:00
|
|
|
s_all_actions = new LibThread::Lockable<Queue<Function<void()>>>();
|
2019-09-21 22:17:53 +00:00
|
|
|
s_background_thread = &LibThread::Thread::construct(background_thread_func).leak_ref();
|
2019-08-25 15:55:56 +00:00
|
|
|
s_background_thread->set_name("Background thread");
|
|
|
|
s_background_thread->start();
|
|
|
|
}
|
|
|
|
|
2019-08-25 20:51:27 +00:00
|
|
|
LibThread::Lockable<Queue<Function<void()>>>& LibThread::BackgroundActionBase::all_actions()
|
2019-08-25 15:55:56 +00:00
|
|
|
{
|
|
|
|
if (s_all_actions == nullptr)
|
|
|
|
init();
|
|
|
|
return *s_all_actions;
|
|
|
|
}
|
|
|
|
|
|
|
|
LibThread::Thread& LibThread::BackgroundActionBase::background_thread()
|
|
|
|
{
|
|
|
|
if (s_background_thread == nullptr)
|
|
|
|
init();
|
|
|
|
return *s_background_thread;
|
|
|
|
}
|