Search code examples
c#multithreadingcircular-buffer

Circular buffer with two indexes


I would like to made a circular buffer which would have two indexes:

  • WriteIndex (controlled by first thread) to write new value in buffer
  • ReadIndex (controlled by second thread) to read value from buffer and analyse it

So, how can I pause the Thread when two indexes are in the same position. I mean, if u didn't write any new data, you can't read it, so if writeindex and readindex are at the same position, you have to only write new data, not read it.

How to block thread untill something happen?


Solution

  • What you're looking for is already in the BCL: BlockingCollection<T>.

    It is thread-safe: it has an Add() method to add items and a blocking Take() method that blocks ("pauses the calling thread") until an item is available.

    As mentioned in a now-removed comment: this is indeed not truly a circular buffer that disposes or overwrites items once the maximum has been reached. You can set an upper bound to the collection size though; this will make Add() block until there is more space.