BackgroundAction.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <LibThread/BackgroundAction.h>
  2. #include <LibThread/Thread.h>
  3. #include <LibThread/Lock.h>
  4. #include <AK/Queue.h>
  5. static LibThread::Lockable<Queue<Function<void()>>>* s_all_actions;
  6. static LibThread::Thread* s_background_thread;
  7. static int background_thread_func()
  8. {
  9. while (true) {
  10. Function<void()> work_item;
  11. {
  12. LOCKER(s_all_actions->lock());
  13. if (!s_all_actions->resource().is_empty())
  14. work_item = s_all_actions->resource().dequeue();
  15. }
  16. if (work_item)
  17. work_item();
  18. else
  19. sleep(1);
  20. }
  21. ASSERT_NOT_REACHED();
  22. }
  23. static void init()
  24. {
  25. s_all_actions = new LibThread::Lockable<Queue<Function<void()>>>();
  26. s_background_thread = &LibThread::Thread::construct(background_thread_func).leak_ref();
  27. s_background_thread->set_name("Background thread");
  28. s_background_thread->start();
  29. }
  30. LibThread::Lockable<Queue<Function<void()>>>& LibThread::BackgroundActionBase::all_actions()
  31. {
  32. if (s_all_actions == nullptr)
  33. init();
  34. return *s_all_actions;
  35. }
  36. LibThread::Thread& LibThread::BackgroundActionBase::background_thread()
  37. {
  38. if (s_background_thread == nullptr)
  39. init();
  40. return *s_background_thread;
  41. }