taskrunner.go 644 B

12345678910111213141516171819202122232425262728293031
  1. package threading
  2. import (
  3. "git.i2edu.net/i2/go-zero/core/lang"
  4. "git.i2edu.net/i2/go-zero/core/rescue"
  5. )
  6. // A TaskRunner is used to control the concurrency of goroutines.
  7. type TaskRunner struct {
  8. limitChan chan lang.PlaceholderType
  9. }
  10. // NewTaskRunner returns a TaskRunner.
  11. func NewTaskRunner(concurrency int) *TaskRunner {
  12. return &TaskRunner{
  13. limitChan: make(chan lang.PlaceholderType, concurrency),
  14. }
  15. }
  16. // Schedule schedules a task to run under concurrency control.
  17. func (rp *TaskRunner) Schedule(task func()) {
  18. rp.limitChan <- lang.Placeholder
  19. go func() {
  20. defer rescue.Recover(func() {
  21. <-rp.limitChan
  22. })
  23. task()
  24. }()
  25. }