BackgroundAction.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Queue.h>
  7. #include <LibThreading/BackgroundAction.h>
  8. #include <LibThreading/Lock.h>
  9. #include <LibThreading/Thread.h>
  10. static Threading::Lockable<Queue<Function<void()>>>* s_all_actions;
  11. static Threading::Thread* s_background_thread;
  12. static intptr_t background_thread_func()
  13. {
  14. while (true) {
  15. Function<void()> work_item;
  16. {
  17. Threading::Locker locker(s_all_actions->lock());
  18. if (!s_all_actions->resource().is_empty())
  19. work_item = s_all_actions->resource().dequeue();
  20. }
  21. if (work_item)
  22. work_item();
  23. else
  24. sleep(1);
  25. }
  26. VERIFY_NOT_REACHED();
  27. }
  28. static void init()
  29. {
  30. s_all_actions = new Threading::Lockable<Queue<Function<void()>>>();
  31. s_background_thread = &Threading::Thread::construct(background_thread_func).leak_ref();
  32. s_background_thread->set_name("Background thread");
  33. s_background_thread->start();
  34. }
  35. Threading::Lockable<Queue<Function<void()>>>& Threading::BackgroundActionBase::all_actions()
  36. {
  37. if (s_all_actions == nullptr)
  38. init();
  39. return *s_all_actions;
  40. }
  41. Threading::Thread& Threading::BackgroundActionBase::background_thread()
  42. {
  43. if (s_background_thread == nullptr)
  44. init();
  45. return *s_background_thread;
  46. }