WorkQueue.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/IntrusiveList.h>
  8. #include <Kernel/Forward.h>
  9. namespace Kernel {
  10. extern WorkQueue* g_io_work;
  11. class WorkQueue {
  12. AK_MAKE_NONCOPYABLE(WorkQueue);
  13. AK_MAKE_NONMOVABLE(WorkQueue);
  14. public:
  15. static void initialize();
  16. WorkQueue(const char*);
  17. void queue(void (*function)(void*), void* data = nullptr, void (*free_data)(void*) = nullptr)
  18. {
  19. auto* item = new WorkItem; // TODO: use a pool
  20. item->function = [function, data, free_data] {
  21. function(data);
  22. if (free_data)
  23. free_data(data);
  24. };
  25. do_queue(item);
  26. }
  27. template<typename Function>
  28. void queue(Function function)
  29. {
  30. auto* item = new WorkItem; // TODO: use a pool
  31. item->function = Function(function);
  32. do_queue(item);
  33. }
  34. private:
  35. struct WorkItem {
  36. IntrusiveListNode<WorkItem> m_node;
  37. Function<void()> function;
  38. };
  39. void do_queue(WorkItem*);
  40. RefPtr<Thread> m_thread;
  41. WaitQueue m_wait_queue;
  42. IntrusiveList<WorkItem, RawPtr<WorkItem>, &WorkItem::m_node> m_items;
  43. Spinlock<u8> m_lock;
  44. };
  45. }