1 `folly/ProducerConsumerQueue.h`
2 -------------------------------
4 The `folly::ProducerConsumerQueue` class is a one-producer
5 one-consumer queue with very low synchronization overhead.
7 The queue must be created with a fixed maximum size (and allocates
8 that many cells of sizeof(T)), and it provides just a few simple
11 * `read`: Attempt to read the value at the front to the queue into a variable,
12 returns `false` iff queue was empty.
13 * `write`: Emplace a value at the end of the queue, returns `false` iff the
15 * `frontPtr`: Retrieve a pointer to the item at the front of the queue, or
16 `nullptr` if it is empty.
17 * `popFront`: Remove the item from the front of the queue (queue must not be
19 * `isEmpty`: Check if the queue is empty.
20 * `isFull`: Check if the queue is full.
21 * `sizeGuess`: Returns the number of entries in the queue. Because of the
22 way we coordinate threads, this guess could be slightly wrong
23 when called by the producer/consumer thread, and it could be
24 wildly inaccurate if called from any other threads. Hence,
25 only call from producer/consumer threads!
27 All of these operations are wait-free. The read operations (including
28 `frontPtr` and `popFront`) and write operations must only be called by the
29 reader and writer thread, respectively. `isFull`, `isEmpty`, and `sizeGuess`
30 may be called by either thread, but the return values from `read`, `write`, or
31 `frontPtr` are sufficient for most cases.
33 `write` may fail if the queue is full, and `read` may fail if the queue is
34 empty, so in many situations it is important to choose the queue size such that
35 the queue filling or staying empty for long is unlikely.
40 A toy example that doesn't really do anything useful:
43 folly::ProducerConsumerQueue<folly::fbstring> queue{size};
45 std::thread reader([&queue] {
48 while (!queue.read(str)) {
49 //spin until we get a value
59 folly::fbstring str = source();
60 while (!queue.write(str)) {
61 //spin until the queue has room
67 Alternatively, the consumer may be written as follows to use the 'front' value
68 in place, thus avoiding moves or copies:
71 std::thread reader([&queue] {
73 folly::fbstring* pval;
75 pval = queue.frontPtr();
76 } while (!pval); // spin until we get a value;