Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. template<typename T, uint size = 1>
  2. struct Queue
  3. {
  4.     bool push(const T& element)
  5.     {
  6.         uint oldWritePosition = writePosition.load(std::memory_order_relaxed);
  7.         while (writePosition.compare_exchange_weak(oldWritePosition, getPositionAfter(oldWritePosition))) {
  8.             if (getPositionAfter(oldWritePosition) == readPosition.load()) {
  9.                 //"pointing to the same area");
  10.                 return false;
  11.             }
  12.  
  13.             ringBuffer[oldWritePosition] = element;
  14.             return true;
  15.         }
  16.         return false;
  17.     }
  18.  
  19.     bool pop(T& element)
  20.     {
  21.         uint oldWritePosition = writePosition.load(std::memory_order_relaxed);
  22.         uint oldReadPosition = readPosition.load(std::memory_order_relaxed);
  23.         while (readPosition.compare_exchange_strong(oldReadPosition, getPositionAfter(oldReadPosition))) {
  24.             if (oldWritePosition == oldReadPosition) {
  25.                 //"pointing to the same area");
  26.                 return false;
  27.             }
  28.  
  29.             element = ringBuffer[oldReadPosition];
  30.             return true;
  31.         } return false;
  32.     }
  33.  
  34.     constexpr uint getPositionAfter(uint position) noexcept
  35.     {
  36.         return ++position == ringBufferSize ? 0 : position;
  37.     }
  38.  
  39.     static constexpr uint ringBufferSize = size + 1;
  40.     T ringBuffer[ringBufferSize];
  41.     std::atomic<uint> writePosition = 0;
  42.     std::atomic<uint> readPosition = 0;
  43. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement