Search code examples
c++visual-c++parallel-processingvisual-studio-2010concurrency-runtime

Number of messages in 'unbounded_buffer'


The class Concurrency::unbounded_buffer can store any number of messages. But how to know number of pending (not received) messages?


Solution

  • There's no functionality built in to do this.

    What you can do is atomically increment/decrement an integer alongside it, but know that this won't be a reliable count (only a ballpark) if it's being accessed concurrently.

    long count;
    Concurrency::unbounded_buffer<T> buffer;
    
    if(Concurrency::send(buffer, T()))
    {
        long new_count = _InterlockedIncrement(&count);
    }
    

    And elsewhere:

    T value = Concurrency::receive(buffer);
    long new_count = _InterlockedDecrement(&count);
    

    You'll find the _Interlocked functions in <intrin.h>.