Boost documentation for spsc_queue
says:
read_available()
: Thread-safe and wait-free, should only be called from the producer thread
write_available()
: Thread-safe and wait-free, should only be called from the consumer thread
I would expect the most common use case to be just the other way around: producer thread (thread writing data to the queue) would need write_available()
, and consumer thread (thread reading data from the queue) would need read_available()
.
If I need to know how much I can write to the queue in the producer thread, should I use QUEUE_CAPACITY - read_available()
?
Any kind of size assessment is going to be a race in the lockfree world.
Simple reason being that the size might be changed on other threads before you act on the "measured size".
Single-Producer/Single-Consumer is special in the sense that the consumer knows nobody else can read from the the queue (so "read_available" will never decrease unless the consumer reads it itself). Similarly for the producer side.
It is clear that
write_available
is what you need. Sure, it could be more by the time you actually write, but you can't get more accurate. At least it will never be less (after all there is only 1 producer thread).I heartily suggest using the range-push shown here to automatically push the exact number of items possible. E.g.: