c-ringbuf
c-ringbuf copied to clipboard
Is this library thread safe?
Can it be used in a multi-producer and multi-consumer thread environment?
It may work, depending on your compiler and your CPU architecture, but I would not depend on it. The only way to do this portably and safely would be to add pthread
support. I have avoided that to date because the primary goal of this project was to provide a portable, bug-free ring buffer implementation, rather than a particularly fast one.
(Apparently C11 may make this possible as well? See https://github.com/dhess/c-ringbuf/pull/4)
I am using this in a multi-threaded environment. Line 282 in ringbuf.c needs to be removed to work correctly:
assert(count + ringbuf_bytes_used(src) == bytes_used);
This will fail if an item is added to the ring buffer in the middle of the ringbuf_memcpy_from() call.
There are many more changes than that required to guarantee that this implementation will work in a multi-threaded program, I’m afraid. It may happen to work for you on a particular CPU when compiled with a particular compiler, but it’s not something you should depend on.
As an aside, you can disable assert()
statements in C by defining the NDEBUG
macro at compile time. See https://en.cppreference.com/w/c/error/assert
I use these: https://github.com/wizard97/Embedded_RingBuf_CPP -- it works fine.