routinetoken.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package otherutils
  2. import "log"
  3. type RoutineTokens struct {
  4. semaRoutine chan struct{}
  5. }
  6. func NewRoutineTokens(tokenNum int) *RoutineTokens {
  7. if tokenNum <= 0 {
  8. tokenNum = 1
  9. }
  10. rt := new(RoutineTokens)
  11. rt.semaRoutine = make(chan struct{}, tokenNum)
  12. return rt
  13. }
  14. // Init和NewRoutineTokens只用调用一个
  15. func (m *RoutineTokens) Init(tokenNum int) {
  16. if tokenNum <= 0 {
  17. tokenNum = 1
  18. }
  19. m.semaRoutine = make(chan struct{}, tokenNum)
  20. }
  21. func (m *RoutineTokens) Acquire() {
  22. if m.semaRoutine == nil {
  23. log.Panic("RoutineTokens chan not init")
  24. return
  25. }
  26. m.semaRoutine <- struct{}{}
  27. }
  28. func (m *RoutineTokens) TryAcquire() bool {
  29. if m.semaRoutine == nil {
  30. log.Panic("RoutineTokens chan not init")
  31. return false
  32. }
  33. select {
  34. case m.semaRoutine <- struct{}{}:
  35. return true
  36. default:
  37. return false
  38. }
  39. }
  40. // 准备废弃
  41. func (m *RoutineTokens) Get() {
  42. if m.semaRoutine == nil {
  43. log.Panic("RoutineTokens chan not init")
  44. return
  45. }
  46. m.semaRoutine <- struct{}{}
  47. }
  48. func (m *RoutineTokens) Release() {
  49. if m.semaRoutine == nil {
  50. log.Panic("RoutineTokens chan not init")
  51. return
  52. }
  53. <-m.semaRoutine
  54. }