WorkQueue.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <Kernel/Process.h>
  8. #include <Kernel/Sections.h>
  9. #include <Kernel/WaitQueue.h>
  10. #include <Kernel/WorkQueue.h>
  11. namespace Kernel {
  12. WorkQueue* g_io_work;
  13. UNMAP_AFTER_INIT void WorkQueue::initialize()
  14. {
  15. g_io_work = new WorkQueue("IO WorkQueue");
  16. }
  17. UNMAP_AFTER_INIT WorkQueue::WorkQueue(StringView name)
  18. {
  19. RefPtr<Thread> thread;
  20. auto name_kstring = KString::try_create(name);
  21. if (name_kstring.is_error())
  22. TODO();
  23. (void)Process::create_kernel_process(thread, name_kstring.release_value(), [this] {
  24. for (;;) {
  25. WorkItem* item;
  26. bool have_more;
  27. m_items.with([&](auto& items) {
  28. item = items.take_first();
  29. have_more = !items.is_empty();
  30. });
  31. if (item) {
  32. item->function();
  33. delete item;
  34. if (have_more)
  35. continue;
  36. }
  37. [[maybe_unused]] auto result = m_wait_queue.wait_on({});
  38. }
  39. });
  40. // If we can't create the thread we're in trouble...
  41. m_thread = thread.release_nonnull();
  42. }
  43. void WorkQueue::do_queue(WorkItem* item)
  44. {
  45. m_items.with([&](auto& items) {
  46. items.append(*item);
  47. });
  48. m_wait_queue.wake_one();
  49. }
  50. }