semaphore.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package semaphore provides a weighted semaphore implementation.
  5. package semaphore // import "golang.org/x/sync/semaphore"
  6. import (
  7. "container/list"
  8. "context"
  9. "sync"
  10. )
  11. type waiter struct {
  12. n int64
  13. ready chan<- struct{} // Closed when semaphore acquired.
  14. }
  15. // NewWeighted creates a new weighted semaphore with the given
  16. // maximum combined weight for concurrent access.
  17. func NewWeighted(n int64) *Weighted {
  18. w := &Weighted{size: n}
  19. return w
  20. }
  21. // Weighted provides a way to bound concurrent access to a resource.
  22. // The callers can request access with a given weight.
  23. type Weighted struct {
  24. size int64
  25. cur int64
  26. mu sync.Mutex
  27. waiters list.List
  28. }
  29. // Acquire acquires the semaphore with a weight of n, blocking until resources
  30. // are available or ctx is done. On success, returns nil. On failure, returns
  31. // ctx.Err() and leaves the semaphore unchanged.
  32. func (s *Weighted) Acquire(ctx context.Context, n int64) error {
  33. done := ctx.Done()
  34. s.mu.Lock()
  35. select {
  36. case <-done:
  37. // ctx becoming done has "happened before" acquiring the semaphore,
  38. // whether it became done before the call began or while we were
  39. // waiting for the mutex. We prefer to fail even if we could acquire
  40. // the mutex without blocking.
  41. s.mu.Unlock()
  42. return ctx.Err()
  43. default:
  44. }
  45. if s.size-s.cur >= n && s.waiters.Len() == 0 {
  46. // Since we hold s.mu and haven't synchronized since checking done, if
  47. // ctx becomes done before we return here, it becoming done must have
  48. // "happened concurrently" with this call - it cannot "happen before"
  49. // we return in this branch. So, we're ok to always acquire here.
  50. s.cur += n
  51. s.mu.Unlock()
  52. return nil
  53. }
  54. if n > s.size {
  55. // Don't make other Acquire calls block on one that's doomed to fail.
  56. s.mu.Unlock()
  57. <-done
  58. return ctx.Err()
  59. }
  60. ready := make(chan struct{})
  61. w := waiter{n: n, ready: ready}
  62. elem := s.waiters.PushBack(w)
  63. s.mu.Unlock()
  64. select {
  65. case <-done:
  66. s.mu.Lock()
  67. select {
  68. case <-ready:
  69. // Acquired the semaphore after we were canceled.
  70. // Pretend we didn't and put the tokens back.
  71. s.cur -= n
  72. s.notifyWaiters()
  73. default:
  74. isFront := s.waiters.Front() == elem
  75. s.waiters.Remove(elem)
  76. // If we're at the front and there're extra tokens left, notify other waiters.
  77. if isFront && s.size > s.cur {
  78. s.notifyWaiters()
  79. }
  80. }
  81. s.mu.Unlock()
  82. return ctx.Err()
  83. case <-ready:
  84. // Acquired the semaphore. Check that ctx isn't already done.
  85. // We check the done channel instead of calling ctx.Err because we
  86. // already have the channel, and ctx.Err is O(n) with the nesting
  87. // depth of ctx.
  88. select {
  89. case <-done:
  90. s.Release(n)
  91. return ctx.Err()
  92. default:
  93. }
  94. return nil
  95. }
  96. }
  97. // TryAcquire acquires the semaphore with a weight of n without blocking.
  98. // On success, returns true. On failure, returns false and leaves the semaphore unchanged.
  99. func (s *Weighted) TryAcquire(n int64) bool {
  100. s.mu.Lock()
  101. success := s.size-s.cur >= n && s.waiters.Len() == 0
  102. if success {
  103. s.cur += n
  104. }
  105. s.mu.Unlock()
  106. return success
  107. }
  108. // Release releases the semaphore with a weight of n.
  109. func (s *Weighted) Release(n int64) {
  110. s.mu.Lock()
  111. s.cur -= n
  112. if s.cur < 0 {
  113. s.mu.Unlock()
  114. panic("semaphore: released more than held")
  115. }
  116. s.notifyWaiters()
  117. s.mu.Unlock()
  118. }
  119. func (s *Weighted) notifyWaiters() {
  120. for {
  121. next := s.waiters.Front()
  122. if next == nil {
  123. break // No more waiters blocked.
  124. }
  125. w := next.Value.(waiter)
  126. if s.size-s.cur < w.n {
  127. // Not enough tokens for the next waiter. We could keep going (to try to
  128. // find a waiter with a smaller request), but under load that could cause
  129. // starvation for large requests; instead, we leave all remaining waiters
  130. // blocked.
  131. //
  132. // Consider a semaphore used as a read-write lock, with N tokens, N
  133. // readers, and one writer. Each reader can Acquire(1) to obtain a read
  134. // lock. The writer can Acquire(N) to obtain a write lock, excluding all
  135. // of the readers. If we allow the readers to jump ahead in the queue,
  136. // the writer will starve — there is always one token available for every
  137. // reader.
  138. break
  139. }
  140. s.cur += w.n
  141. s.waiters.Remove(next)
  142. close(w.ready)
  143. }
  144. }