24 m_freeItems(capacity),
28 static_assert(ATOMIC_INT_LOCK_FREE == 2);
29 m_spBuffer = std::make_unique<DataType[]>(m_capacity);
30 memset(m_spBuffer.get(), 0,
sizeof(DataType) * m_capacity);
34 int getReadableItemCount()
const {
35 return m_capacity - m_freeItems.load();
38 int getWriteableItemCount()
const {
39 return m_freeItems.load();
42 int read(DataType * pData,
int max) {
44 int readableItemCount = getReadableItemCount();
45 if (readableItemCount == 0)
48 int totalItemsToRead = std::min(readableItemCount, max);
49 int itemsLeftToRead = totalItemsToRead;
51 if (m_readIndex + itemsLeftToRead >= m_capacity) {
52 int itemsAvailableUntilEnd = m_capacity - m_readIndex;
53 memcpy(pData, m_spBuffer.get() + m_readIndex, itemsAvailableUntilEnd *
sizeof(DataType));
55 itemsLeftToRead -= itemsAvailableUntilEnd;
56 pData += itemsAvailableUntilEnd;
59 if (itemsLeftToRead > 0) {
60 memcpy(pData, m_spBuffer.get() + m_readIndex, itemsLeftToRead *
sizeof(DataType));
61 m_readIndex += itemsLeftToRead;
65 m_freeItems += totalItemsToRead;
66 return totalItemsToRead;
69 int write(DataType * pData,
int numItems) {
71 int writeableItemCount = getWriteableItemCount();
72 if (writeableItemCount == 0)
75 int totalItemsToWrite = std::min(writeableItemCount, numItems);
76 int itemsLeftToWrite = totalItemsToWrite;
78 if ((m_writeIndex + itemsLeftToWrite) >= m_capacity) {
79 int itemsAvailableUntilEnd = m_capacity - m_writeIndex;
80 memcpy(m_spBuffer.get() + m_writeIndex, pData, itemsAvailableUntilEnd *
sizeof(DataType));
82 itemsLeftToWrite -= itemsAvailableUntilEnd;
83 pData += itemsAvailableUntilEnd;
86 if (itemsLeftToWrite > 0) {
87 memcpy(m_spBuffer.get() + m_writeIndex, pData, itemsLeftToWrite *
sizeof(DataType));
88 m_writeIndex += itemsLeftToWrite;
92 m_freeItems -= totalItemsToWrite;
93 return totalItemsToWrite;
98 std::unique_ptr<DataType[]> m_spBuffer;
102 const int m_capacity;
103 std::atomic<int> m_freeItems;
A Ring Buffer for multi-threaded communications.
Definition ring_buffer.hh:19
Definition additive_saw.cc:24