WaitableQueue is a concurrency-safe, unbounded FIFO queue designed for
producer-consumer patterns where Go channels are inconvenient — for example,
when you need flow control without the hard capacity limits of a buffered
channel, or when the number of producers and consumers is dynamic.
When to use WaitableQueue vs Queue
| Situation | Use |
|---|---|
| Single goroutine, no shared access | Queue |
| Multiple goroutines sharing the same queue | WaitableQueue |
| Need to signal consumers when items arrive | WaitableQueue |
| Need producer throttling based on queue depth | WaitableQueue |
Installation
Constructor
Pre-allocates internal storage for this many elements. Must be
≥ 0.The queue depth below which
Dequeue reports QueueIsBelowLowWatermark.
Must be ≥ 0.The queue depth at or above which
Enqueue and Dequeue report
QueueIsAboveHighWatermark. Must be ≥ lowWatermark.Error cases
The constructor returns an error for invalid arguments:| Error variable | Condition |
|---|---|
queue.ErrCapacityIsNegative | initialCapacity < 0 |
queue.ErrLowWatermarkIsNegative | lowWatermark < 0 |
queue.ErrHighWatermarkIsNegative | highWatermark < 0 |
queue.ErrHighWatermarkIsLessThanLowWatermark | lowWatermark > highWatermark |
Interface
Enqueue
WaitableQueueState. Panics if called after Close().
Dequeue
ok is false,
e is the zero value, and result is QueueIsBelowLowWatermark.
WaitChan
select statement to avoid busy-polling.
After receiving on this channel, always call Dequeue in a loop until ok is
false — a single signal may correspond to multiple enqueued items.
Close
WaitChan. Once closed, calling Enqueue panics. You should drain any
remaining items with Dequeue after Close returns. In most cases, Close
should be called only by the producer.
Queue states
WaitableQueueState is returned by Enqueue and Dequeue to describe the
current depth of the queue relative to the watermarks you configured.
| Constant | Meaning |
|---|---|
QueueIsEmpty | Set at creation only; not returned during normal operation. |
QueueIsBelowLowWatermark | Depth is at or below lowWatermark. Returned by Dequeue when the queue is empty. |
QueueIsNominal | Depth is between the low and high watermarks. Normal operating range. |
QueueIsAboveHighWatermark | Depth is at or above highWatermark. Consider scaling consumers or throttling producers. |
QueueIsNearSaturation | Depth is approaching the saturation threshold (computed from initialCapacity and highWatermark). Emergency signal; consider immediate load shedding. |
Producer-consumer pattern
The typical pattern is one or more producer goroutines callingEnqueue, and
one or more consumer goroutines selecting on WaitChan and then draining with
Dequeue.
Flow control with WaitChan
Use the state returned byDequeue to scale consumers dynamically:
WaitableQueue is concurrency-safe. Its Len() method (if called) is not
atomic with respect to Enqueue/Dequeue and should only be used for
observability or debugging, not for control flow decisions.