diff --git a/CMakeLists.txt b/CMakeLists.txt index ee3cf793..74197f9f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -405,7 +405,8 @@ set(PUBLICHEADERS include/aare/to_string.hpp include/aare/utils/task.hpp include/aare/utils/ifstream_helpers.hpp - include/aare/utils/math_helpers.hpp) + include/aare/utils/math_helpers.hpp + include/aare/utils/RingBufferPool.hpp) set(SourceFiles ${CMAKE_CURRENT_SOURCE_DIR}/src/calibration.cpp @@ -514,6 +515,7 @@ if(AARE_TESTS) ${CMAKE_CURRENT_SOURCE_DIR}/src/RawSubFile.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/ROI.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/utils/task.test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/utils/RingBufferPool.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/to_string.test.cpp) target_sources(tests PRIVATE ${TestSources}) endif() diff --git a/include/aare/DataSetAggregation.hpp b/include/aare/DataSetAggregation.hpp index a1a23c21..53d30af9 100644 --- a/include/aare/DataSetAggregation.hpp +++ b/include/aare/DataSetAggregation.hpp @@ -1,142 +1,16 @@ #pragma once #include "aare/File.hpp" #include "aare/MultiThreadedFileReader.hpp" +#include "aare/utils/RingBufferPool.hpp" #include "aare/utils/math_helpers.hpp" #include #include -#include #include #include -#include -#include #include namespace aare { -/** - * @brief Ring buffer of slots shared between one producer and a fixed number - * of consumers. Item i is stored in slot i % size(). The producer can only - * overwrite a slot once all consumers released the item stored in it, and a - * consumer can only read item i once the producer committed it. - * Calling abort() wakes up all waiting threads. - */ -template class BufferPool { - public: - /** - * @param size number of slots in the pool - * @param num_consumers number of consumers that read every item - * @param initializer callable returning the initial ItemType of a slot - */ - template - BufferPool(size_t size, size_t num_consumers, Func initializer) - : m_num_consumers(num_consumers), m_item_in_slot(size, no_item), - m_pending_consumers(size, 0) { - if (size == 0) - throw std::invalid_argument("BufferPool size must be at least 1"); - m_buffers.reserve(size); - for (size_t i = 0; i < size; ++i) { - m_buffers.emplace_back(initializer()); - } - } - - /// @brief Get the number of slots in the buffer pool. - /// @return The number of slots in the buffer pool. - size_t size() const { return m_buffers.size(); } - - /** - * @brief Block until the slot of item i is free (e.g. all consumers have - * read it) to be written. - * @return the buffer to write item i into or nullptr if aborted - */ - ItemType *acquire_write(size_t i) { - const size_t slot = i % size(); - std::unique_lock lock(m_mtx); - m_cv_free.wait( - lock, [&] { return m_abort || m_pending_consumers[slot] == 0; }); - if (m_abort) - return nullptr; - return &m_buffers[slot]; - } - - /** - * @brief Mark item i as written and wake up the consumers. - */ - void commit_write(size_t i) { - const size_t slot = i % size(); - { - std::lock_guard lock(m_mtx); - m_item_in_slot[slot] = i; - m_pending_consumers[slot] = m_num_consumers; - } - m_cv_loaded.notify_all(); - } - - /** - * @brief Block until item i has been written. - * @return the buffer holding item i or nullptr if aborted - */ - const ItemType *acquire_read(size_t i) { - const size_t slot = i % size(); - std::unique_lock lock(m_mtx); - m_cv_loaded.wait(lock, - [&] { return m_abort || m_item_in_slot[slot] == i; }); - if (m_abort) - return nullptr; - return &m_buffers[slot]; - } - - /** - * @brief Signal that this consumer no longer needs item i. Once all - * consumers released it the slot can be reused by the producer. - */ - void release_read(size_t i) { - const size_t slot = i % size(); - bool slot_free = false; - { - std::lock_guard lock(m_mtx); - slot_free = --m_pending_consumers[slot] == 0; - } - if (slot_free) - m_cv_free.notify_one(); - } - - /** - * @brief Wake up all waiting threads, acquire_* returns nullptr from now - * on. - */ - void abort() { - { - std::lock_guard lock(m_mtx); - m_abort = true; - } - m_cv_loaded.notify_all(); - m_cv_free.notify_all(); - } - - private: - size_t m_num_consumers; - std::vector m_buffers; - - static constexpr size_t no_item = std::numeric_limits::max(); - - // per slot: - /// @brief Index of the item currently committed to the slot. - std::vector m_item_in_slot; // store the item - boolean flag need to - // set back to false -> - std::vector m_pending_consumers; - - std::mutex m_mtx; - /// @brief Condition variable to notify consumers that an item has been - /// loaded. - std::condition_variable m_cv_loaded; - /// @brief Condition variable to notify producers that a slot is free to - /// overwrite. - std::condition_variable m_cv_free; - - /// @brief Flag to indicate if the buffer pool should be aborted. - bool m_abort{false}; -}; - /** * @brief Compute the block mean over several frames per sample stored in a * file. Function spawns num_processing_threads + num_reader_threads + 1 threads @@ -193,7 +67,7 @@ NDArray block_mean(const std::filesystem::path &path, constexpr size_t num_buffers = 4; // TODO: random for now reading much slower - small buffer is enough - BufferPool> buffers( + RingBufferPool> buffers( num_buffers, num_processing_threads, [&mean_over_num_frames, &rows, &cols] { return NDArray(std::array{ diff --git a/include/aare/utils/RingBufferPool.hpp b/include/aare/utils/RingBufferPool.hpp new file mode 100644 index 00000000..b05009b8 --- /dev/null +++ b/include/aare/utils/RingBufferPool.hpp @@ -0,0 +1,139 @@ +#include +#include +#include +#include +#include +#include +#include + +namespace aare { +/** + * @brief Ring buffer of slots shared between one producer and a fixed number + * of consumers. Item i is stored in slot i % size(). The producer can only + * overwrite a slot once all consumers released the item stored in it, and a + * consumer can only read item i once the producer committed it. + * Calling abort() wakes up all waiting threads. + */ +template class RingBufferPool { + public: + /** + * @param size number of slots in the pool + * @param num_consumers number of consumers that read every item + * @param initializer callable returning the initial ItemType of a slot + */ + template + RingBufferPool(size_t size, size_t num_consumers, Func initializer) + : m_num_consumers(num_consumers), m_item_in_slot(size, no_item), + m_pending_consumers(size, 0) { + if (size == 0) + throw std::invalid_argument( + "RingBufferPool size must be at least 1"); + m_buffers.reserve(size); + for (size_t i = 0; i < size; ++i) { + m_buffers.emplace_back(initializer()); + } + } + + /// @brief Get the number of slots in the buffer pool. + /// @return The number of slots in the buffer pool. + size_t size() const { return m_buffers.size(); } + + /** + * @brief Block until the slot of item i is free (e.g. all consumers have + * read it) to be written. + * @return the buffer to write item i into or nullptr if aborted + */ + ItemType *acquire_write(size_t i) { + const size_t slot = i % size(); + std::unique_lock lock(m_mtx); + m_cv_free.wait( + lock, [&] { return m_abort || m_pending_consumers[slot] == 0; }); + if (m_abort) + return nullptr; + return &m_buffers[slot]; + } + + /** + * @brief Mark item i as written and wake up the consumers. + */ + void commit_write(size_t i) { + const size_t slot = i % size(); + { + std::lock_guard lock(m_mtx); + m_item_in_slot[slot] = i; + m_pending_consumers[slot] = m_num_consumers; + } + m_cv_loaded.notify_all(); + } + + /** + * @brief Block until item i has been written. + * @return the buffer holding item i or nullptr if aborted + */ + const ItemType *acquire_read(size_t i) { + const size_t slot = i % size(); + std::unique_lock lock(m_mtx); + m_cv_loaded.wait(lock, + [&] { return m_abort || m_item_in_slot[slot] == i; }); + if (m_abort) + return nullptr; + return &m_buffers[slot]; + } + + /** + * @brief Signal that this consumer no longer needs item i. Once all + * consumers released it the slot can be reused by the producer. + */ + void release_read(size_t i) { + const size_t slot = i % size(); + bool slot_free = false; + { + std::lock_guard lock(m_mtx); + if (m_item_in_slot[slot] != i) + throw std::logic_error( + "release_read called for item not in slot"); + slot_free = --m_pending_consumers[slot] == 0; + } + if (slot_free) { + m_cv_free.notify_one(); + } + } + + /** + * @brief Wake up all waiting threads, acquire_* returns nullptr from now + * on. + */ + void abort() { + { + std::lock_guard lock(m_mtx); + m_abort = true; + } + m_cv_loaded.notify_all(); + m_cv_free.notify_all(); + } + + private: + size_t m_num_consumers; + std::vector m_buffers; + + static constexpr size_t no_item = std::numeric_limits::max(); + + // per slot: + /// @brief Index of the item currently committed to the slot. + std::vector m_item_in_slot; // store the item - boolean flag need to + // set back to false -> + std::vector m_pending_consumers; + + std::mutex m_mtx; + /// @brief Condition variable to notify consumers that an item has been + /// loaded. + std::condition_variable m_cv_loaded; + /// @brief Condition variable to notify producers that a slot is free to + /// overwrite. + std::condition_variable m_cv_free; + + /// @brief Flag to indicate if the buffer pool should be aborted. + bool m_abort{false}; +}; + +} // namespace aare \ No newline at end of file diff --git a/src/DataSetAggregation.cpp b/src/DataSetAggregation.cpp index a2becc9a..470f3e75 100644 --- a/src/DataSetAggregation.cpp +++ b/src/DataSetAggregation.cpp @@ -60,7 +60,7 @@ NDArray mean_current_source(const std::filesystem::path &path, constexpr size_t num_buffers = 4; // TODO: random for now reading much // slower - small buffer is enough - BufferPool> buffers( + RingBufferPool> buffers( num_buffers, num_processing_threads, [&num_rows, &num_cols, &frames_per_sample] { return NDArray( diff --git a/src/utils/RingBufferPool.test.cpp b/src/utils/RingBufferPool.test.cpp new file mode 100644 index 00000000..581f05d6 --- /dev/null +++ b/src/utils/RingBufferPool.test.cpp @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/utils/RingBufferPool.hpp" + +#include + +TEST_CASE("RingBufferPool cant overwrite before all consumers release", + "[RingBufferPool]") { + constexpr size_t pool_size = 8; + constexpr size_t num_consumers = 3; + + // Create a RingBufferPool with integers initialized to 0 + aare::RingBufferPool ring_buffer(pool_size, num_consumers, + []() { return 0; }); + + // Test acquiring and committing writes + for (size_t i = 0; i < pool_size; ++i) { + int *buffer = ring_buffer.acquire_write(i); + REQUIRE(buffer != nullptr); + *buffer = static_cast(i); + ring_buffer.commit_write(i); + } + + // Test acquiring reads + for (size_t i = 0; i < pool_size; ++i) { + const int *buffer = ring_buffer.acquire_read(i); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == static_cast(i)); + ring_buffer.release_read(i); + } + + const size_t next_buffer = pool_size; // This will wrap around to slot 0 + const size_t slot_to_write = next_buffer % pool_size; + // Producer cannot acquire a write slot until all consumers have released it + std::thread producer_thread([&ring_buffer, next_buffer]() { + int *buffer = ring_buffer.acquire_write(next_buffer); + REQUIRE(buffer != nullptr); + *buffer = static_cast(next_buffer); + ring_buffer.commit_write(next_buffer); + }); + + // Remaining consumers read the items + for (size_t i = 1; i < num_consumers; ++i) { + const int *buffer = ring_buffer.acquire_read(slot_to_write); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == static_cast(0)); + ring_buffer.release_read(slot_to_write); + } + + producer_thread.join(); + + // written correctly + { + const int *buffer = ring_buffer.acquire_read(next_buffer); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == static_cast(next_buffer)); + } + for (size_t i = 1; i < pool_size; ++i) { + const int *buffer = ring_buffer.acquire_read(i); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == static_cast(i)); + ring_buffer.release_read(i); + } + + // Test aborting the pool + ring_buffer.abort(); + int *buffer_after_abort = ring_buffer.acquire_write(6); + REQUIRE(buffer_after_abort == nullptr); +} + +TEST_CASE("cant read if not written", "[RingBufferPool]") { + constexpr size_t pool_size = 2; + constexpr size_t num_consumers = 2; + + aare::RingBufferPool ring_buffer(pool_size, num_consumers, + []() { return 0; }); + + const int value_first_slot = 50; + const int value_second_slot = 10; + + { + int *buffer = ring_buffer.acquire_write(0); + *buffer = value_first_slot; + ring_buffer.commit_write(0); + } + + { + const int *buffer = ring_buffer.acquire_read(0); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == value_first_slot); + ring_buffer.release_read(0); + } + bool could_read = false; + + std::thread consumer_thread([&ring_buffer, &could_read]() { + // Try to acquire read for an item that hasn't been written yet + const int *buffer = ring_buffer.acquire_read(1); + could_read = (buffer != nullptr); + REQUIRE(*buffer == value_second_slot); + }); + + { + const int *buffer = ring_buffer.acquire_read(0); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == value_first_slot); + ring_buffer.release_read(0); + } + + REQUIRE(could_read == false); + + { + int *buffer = ring_buffer.acquire_write(0); + REQUIRE(buffer != nullptr); + *buffer = value_first_slot; + ring_buffer.commit_write(0); + } + REQUIRE(could_read == false); + + { + int *buffer = ring_buffer.acquire_write(1); + REQUIRE(buffer != nullptr); + *buffer = value_second_slot; + ring_buffer.commit_write(1); + } + consumer_thread.join(); + + REQUIRE(could_read == true); +} \ No newline at end of file