| 1 | // Copyright The OpenTelemetry Authors |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| 4 | package queue // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue" |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "sync" |
| 9 | ) |
| 10 | |
| 11 | // cond is equivalent with sync.Cond, but context.Context aware. |
| 12 | // Which means Wait() will return if context is done before any signal is received. |
| 13 | // Also, it requires the caller to hold the c.L during all calls. |
| 14 | type cond struct { |
| 15 | L sync.Locker |
| 16 | ch chan struct{} |
| 17 | waiting int64 |
| 18 | } |
| 19 | |
| 20 | func newCond(l sync.Locker) *cond { |
| 21 | return &cond{L: l, ch: make(chan struct{}, 1)} |
| 22 | } |
| 23 | |
| 24 | // Signal wakes one goroutine waiting on c, if there is any. |
| 25 | // It requires for the caller to hold c.L during the call. |
| 26 | func (c *cond) Signal() { |
| 27 | if c.waiting == 0 { |
| 28 | return |
| 29 | } |
| 30 | c.waiting-- |
| 31 | c.ch <- struct{}{} |
| 32 | } |
| 33 | |
| 34 | // Broadcast wakes all goroutines waiting on c. |
| 35 | // It requires for the caller to hold c.L during the call. |
| 36 | func (c *cond) Broadcast() { |
| 37 | for ; c.waiting > 0; c.waiting-- { |
| 38 | c.ch <- struct{}{} |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // Wait atomically unlocks c.L and suspends execution of the calling goroutine. After later resuming execution, Wait locks c.L before returning. |
| 43 | func (c *cond) Wait(ctx context.Context) error { |
| 44 | c.waiting++ |
| 45 | c.L.Unlock() |
| 46 | select { |
| 47 | case <-ctx.Done(): |
| 48 | c.L.Lock() |
| 49 | if c.waiting == 0 { |
| 50 | // If waiting is 0, it means that there was a signal sent and nobody else waits for it. |
| 51 | // Consume it, so that we don't unblock other consumer unnecessary, |
| 52 | // or we don't block the producer because the channel buffer is full. |
| 53 | <-c.ch |
| 54 | } else { |
| 55 | // Decrease the number of waiting routines. |
| 56 | c.waiting-- |
| 57 | } |
| 58 | return ctx.Err() |
| 59 | case <-c.ch: |
| 60 | c.L.Lock() |
| 61 | return nil |
| 62 | } |
| 63 | } |