github.com/lingyao2333/mo-zero@v1.4.1/core/threading/taskrunner.go (about)

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