limit.go 717 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package syncx
  2. import (
  3. "errors"
  4. "github.com/tal-tech/go-zero/core/lang"
  5. )
  6. var ErrReturn = errors.New("discarding limited token, resource pool is full, someone returned multiple times")
  7. type Limit struct {
  8. pool chan lang.PlaceholderType
  9. }
  10. func NewLimit(n int) Limit {
  11. return Limit{
  12. pool: make(chan lang.PlaceholderType, n),
  13. }
  14. }
  15. func (l Limit) Borrow() {
  16. l.pool <- lang.Placeholder
  17. }
  18. // Return returns the borrowed resource, returns error only if returned more than borrowed.
  19. func (l Limit) Return() error {
  20. select {
  21. case <-l.pool:
  22. return nil
  23. default:
  24. return ErrReturn
  25. }
  26. }
  27. func (l Limit) TryBorrow() bool {
  28. select {
  29. case l.pool <- lang.Placeholder:
  30. return true
  31. default:
  32. return false
  33. }
  34. }