This is a thread-safe, templated circular buffer implemented in C++ that supports any data type. It efficiently manages data in a fixed-size buffer, allowing seamless writing and reading operations without reallocations.
- ✅ Generic Support: Works with
int,float,std::string, or any user-defined type. - ✅ Thread-Safe: Uses
std::mutexto ensure concurrent access safety. - ✅ Efficient Memory Usage: Uses
std::vector<T>internally to manage data efficiently. - ✅ Automatic Wrap-Around: Handles buffer overflow naturally without extra copying.
Simply clone this repository and include the CircularBuffer.h file in your project.
git clone https://github.com/hosein-srj/circular-buffer.gitInclude the header file in your C++ project:
#include "CircularBuffer.h"Instantiate a buffer of any data type:
#include "CircularBuffer.h"
int main() {
CircularBuffer<int16_t> buffer(100); // Buffer for int16_t with size 100
return 0;
}int16_t data[] = {1, 2, 3, 4, 5};
buffer.write(data, 5);auto result = buffer.read(3);
for (auto val : result) {
std::cout << val << " ";
}📌 Output: 1 2 3
if (buffer.isFull(10)) {
std::cout << "Buffer is full!";
}
if (buffer.hasEnoughData(5)) {
std::cout << "Enough data available!";
}buffer.reset(); // Clears all stored data- All functions use
std::mutex(std::lock_guard) to prevent race conditions. - Safe to use in multithreaded environments.
- Locks are applied only where necessary, minimizing performance overhead.
std::copyinstead ofmemcpyfor type safety and generality.- No dynamic allocations during operations, except when resizing in
setUp(). - Optimized wrap-around handling using modular arithmetic.
- Avoids expensive copies, using
std::vector<T>efficiently.
This project is licensed under the MIT License. Feel free to use and modify.
If you’d like to contribute:
- Fork the repo 🍴
- Create a new branch:
git checkout -b feature-name - Commit your changes:
git commit -m "Add feature X" - Push to your branch:
git push origin feature-name - Open a Pull Request 🚀
Developed by [Hosein Seraj]
📧 Email: [hosein.seraj11@gmail.com]
🔗 GitHub: https://github.com/hosein-srj
✔️ Project Overview
✔️ Installation Guide
✔️ Code Usage with Examples
✔️ Thread-Safety Explanation
✔️ Performance Considerations
✔️ License & Contribution Guide