routinetoken.go 637 B

123456789101112131415161718192021222324252627282930313233343536
  1. package coroutine
  2. import (
  3. "leafstalk/log"
  4. "leafstalk/otherutils"
  5. )
  6. type LimitNRoutine struct {
  7. routineTokens *otherutils.RoutineTokens
  8. }
  9. func NewLimitNRoutine(routineNum int) *LimitNRoutine {
  10. lr := new(LimitNRoutine)
  11. lr.routineTokens = otherutils.NewRoutineTokens(routineNum)
  12. return lr
  13. }
  14. // 协程加载
  15. func (r *LimitNRoutine) Go(fprocess func()) {
  16. go func() {
  17. err := r.routineTokens.Acquire()
  18. if err != nil {
  19. log.Errorf("Go run error: %s", err)
  20. return
  21. }
  22. defer func() {
  23. r.routineTokens.Release()
  24. err := recover()
  25. if err != nil {
  26. log.Errorf("Go run error: %s", err)
  27. }
  28. }()
  29. fprocess()
  30. }()
  31. }