WorkQueue.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #pragma once
  8. #include <AK/IntrusiveList.h>
  9. #include <Kernel/Forward.h>
  10. #include <Kernel/Locking/SpinlockProtected.h>
  11. #include <Kernel/WaitQueue.h>
  12. namespace Kernel {
  13. extern WorkQueue* g_io_work;
  14. class WorkQueue {
  15. AK_MAKE_NONCOPYABLE(WorkQueue);
  16. AK_MAKE_NONMOVABLE(WorkQueue);
  17. public:
  18. static void initialize();
  19. void queue(void (*function)(void*), void* data = nullptr, void (*free_data)(void*) = nullptr)
  20. {
  21. auto* item = new WorkItem; // TODO: use a pool
  22. item->function = [function, data, free_data] {
  23. function(data);
  24. if (free_data)
  25. free_data(data);
  26. };
  27. do_queue(item);
  28. }
  29. template<typename Function>
  30. void queue(Function function)
  31. {
  32. auto* item = new WorkItem; // TODO: use a pool
  33. item->function = Function(function);
  34. do_queue(item);
  35. }
  36. private:
  37. explicit WorkQueue(StringView);
  38. struct WorkItem {
  39. public:
  40. IntrusiveListNode<WorkItem> m_node;
  41. Function<void()> function;
  42. };
  43. void do_queue(WorkItem*);
  44. RefPtr<Thread> m_thread;
  45. WaitQueue m_wait_queue;
  46. SpinlockProtected<IntrusiveList<&WorkItem::m_node>> m_items;
  47. };
  48. }