dhess / c-ringbuf

A ring buffer implemented in C
Other
418 stars 143 forks source link

Is this library thread safe? #7

Open skyformat99 opened 6 years ago

skyformat99 commented 6 years ago

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

dhess commented 6 years ago

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 commented 6 years ago

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

j-omega commented 5 years ago

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.

dhess commented 5 years ago

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

JensGrabner commented 5 years ago

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