limit.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Package mhayaSync mhayaSync file from https://github.com/beego/beego/blob/develop/core/utils/safemap.go
  2. package mhayaSync
  3. import cerr "github.com/mhaya/error"
  4. var (
  5. // errReturn indicates that the more than borrowed elements were returned.
  6. errReturn = cerr.Error("discarding limited token, resource pool is full, someone returned multiple times")
  7. placeholder placeholderType
  8. )
  9. type (
  10. placeholderType = struct{}
  11. // Limit controls the concurrent requests.
  12. Limit struct {
  13. pool chan placeholderType
  14. }
  15. )
  16. // NewLimit creates a Limit that can borrow n elements from it concurrently.
  17. func NewLimit(n int) Limit {
  18. return Limit{
  19. pool: make(chan placeholderType, n),
  20. }
  21. }
  22. // Borrow borrows an element from Limit in blocking mode.
  23. func (l Limit) Borrow() {
  24. l.pool <- placeholder
  25. }
  26. // Return returns the borrowed resource, returns error only if returned more than borrowed.
  27. func (l Limit) Return() error {
  28. select {
  29. case <-l.pool:
  30. return nil
  31. default:
  32. return errReturn
  33. }
  34. }
  35. // TryBorrow tries to borrow an element from Limit, in non-blocking mode.
  36. // If success, true returned, false for otherwise.
  37. func (l Limit) TryBorrow() bool {
  38. select {
  39. case l.pool <- placeholder:
  40. return true
  41. default:
  42. return false
  43. }
  44. }