Acquire acquires a token, blocking if necessary until one is available. Returns an error if the context is cancelled or the timeout expires. Uses a fast path to avoid timer allocation when tokens are immediately available.
(ctx context.Context, timeout time.Duration, timeoutErr error)
| 54 | // Returns an error if the context is cancelled or the timeout expires. |
| 55 | // Uses a fast path to avoid timer allocation when tokens are immediately available. |
| 56 | func (s *FastSemaphore) Acquire(ctx context.Context, timeout time.Duration, timeoutErr error) error { |
| 57 | // Check context first |
| 58 | select { |
| 59 | case <-ctx.Done(): |
| 60 | return ctx.Err() |
| 61 | default: |
| 62 | } |
| 63 | |
| 64 | // Try fast path first (no timer needed) |
| 65 | select { |
| 66 | case <-s.tokens: |
| 67 | return nil |
| 68 | default: |
| 69 | } |
| 70 | |
| 71 | // Slow path: need to wait with timeout |
| 72 | timer := semTimers.Get().(*time.Timer) |
| 73 | defer semTimers.Put(timer) |
| 74 | timer.Reset(timeout) |
| 75 | |
| 76 | select { |
| 77 | case <-s.tokens: |
| 78 | if !timer.Stop() { |
| 79 | <-timer.C |
| 80 | } |
| 81 | return nil |
| 82 | case <-ctx.Done(): |
| 83 | if !timer.Stop() { |
| 84 | <-timer.C |
| 85 | } |
| 86 | return ctx.Err() |
| 87 | case <-timer.C: |
| 88 | return timeoutErr |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | // AcquireBlocking acquires a token, blocking indefinitely until one is available. |
| 93 | func (s *FastSemaphore) AcquireBlocking() { |