Documentation ¶
Overview ¶
Package condqueue provides a concurrent queue, on which consumers can wait for an item satisfying a given condition, and producers can add items to wake consumers.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CondQueue ¶
type CondQueue[T any] struct { // contains filtered or unexported fields }
CondQueue is a concurrent queue of items of type T. Consumer goroutines can call CondQueue.AwaitMatchingItem to wait for an item matching a given condition to arrive in the queue. Producer goroutines can call CondQueue.Add, which passes the item to a matching consumer.
A CondQueue must never be copied (initialize it with New to ensure this).
func (*CondQueue[T]) Add ¶ added in v0.2.0
func (queue *CondQueue[T]) Add(item T)
Add checks if the given item is a match for any consumers currently waiting on the queue.
If a matching consumer is found, the consumer is woken and given the item, then removed from the queue. The item is only given to a single consumer (prioritizing older consumers), so any other matching consumers must wait for a later item.
If no matching consumer is found, the item is stored so that future consumers may match on it.
func (*CondQueue[T]) AwaitMatchingItem ¶
func (queue *CondQueue[T]) AwaitMatchingItem( ctx context.Context, isMatch func(item T) bool, ) (matchingItem T, cancelErr error)
AwaitMatchingItem goes through unconsumed items in the queue, and returns an item where isMatch(item) returns true. If no match is found there, it waits until one arrives in the queue.
If ctx is canceled before a match is found, the context's error is returned by calling context.Cause on it. If the context never cancels, e.g. when using context.Background, the error can safely be ignored. If a matching item is never received, and the context never cancels, this may halt the calling goroutine forever. It is therefore advised to use context.WithTimeout or similar.
If multiple concurrent consumers may match on the same item, only one of them will receive the item - i.e., every call to CondQueue.Add corresponds with one returned match from AwaitMatchingItem.