WorkQueue.cpp 1.2 KB

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