LiveEventQueue.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #pragma once
  2. // Lock-free single-producer/single-consumer queues. Used for notes
  3. // played live (UI -> audio, MIDI -> audio) and for recording (MIDI -> UI).
  4. #include <array>
  5. #include <atomic>
  6. #include <cstddef>
  7. #include "core/Scheduler.h"
  8. namespace lynx
  9. {
  10. template <typename T, std::size_t Capacity>
  11. class SpscQueue
  12. {
  13. public:
  14. static_assert ((Capacity & (Capacity - 1)) == 0, "capacity must be a power of 2");
  15. static constexpr std::size_t capacity = Capacity;
  16. // Producer. Returns false if the queue is full (the item is dropped).
  17. bool push (const T& item) noexcept
  18. {
  19. const auto w = writeIndex.load (std::memory_order_relaxed);
  20. const auto next = (w + 1) & (capacity - 1);
  21. if (next == readIndex.load (std::memory_order_acquire))
  22. return false;
  23. items[w] = item;
  24. writeIndex.store (next, std::memory_order_release);
  25. return true;
  26. }
  27. // Consumer.
  28. bool pop (T& out) noexcept
  29. {
  30. const auto r = readIndex.load (std::memory_order_relaxed);
  31. if (r == writeIndex.load (std::memory_order_acquire))
  32. return false;
  33. out = items[r];
  34. readIndex.store ((r + 1) & (capacity - 1), std::memory_order_release);
  35. return true;
  36. }
  37. private:
  38. std::array<T, capacity> items {};
  39. std::atomic<std::size_t> writeIndex { 0 };
  40. std::atomic<std::size_t> readIndex { 0 };
  41. };
  42. using LiveEventQueue = SpscQueue<NoteEvent, 256>;
  43. } // namespace lynx