c-ringbuf icon indicating copy to clipboard operation
c-ringbuf copied to clipboard

Is this library thread safe?

Open skyformat99 opened this issue 6 years ago • 5 comments

Can it be used in a multi-producer and multi-consumer thread environment?

skyformat99 avatar Jun 03 '18 13:06 skyformat99

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.

dhess avatar Jun 03 '18 18:06 dhess

(Apparently C11 may make this possible as well? See https://github.com/dhess/c-ringbuf/pull/4)

dhess avatar Jun 03 '18 18:06 dhess

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.

j-omega avatar May 16 '19 17:05 j-omega

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

dhess avatar May 16 '19 18:05 dhess

I use these: https://github.com/wizard97/Embedded_RingBuf_CPP -- it works fine.

JensGrabner avatar May 17 '19 05:05 JensGrabner