You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/threading/taskrunner.go

32 lines
650 B
Go

4 years ago
package threading
import (
"github.com/tal-tech/go-zero/core/lang"
"github.com/tal-tech/go-zero/core/rescue"
4 years ago
)
// A TaskRunner is used to control the concurrency of goroutines.
4 years ago
type TaskRunner struct {
limitChan chan lang.PlaceholderType
}
// NewTaskRunner returns a TaskRunner.
4 years ago
func NewTaskRunner(concurrency int) *TaskRunner {
return &TaskRunner{
limitChan: make(chan lang.PlaceholderType, concurrency),
}
}
// Schedule schedules a task to run under concurrency control.
4 years ago
func (rp *TaskRunner) Schedule(task func()) {
rp.limitChan <- lang.Placeholder
go func() {
defer rescue.Recover(func() {
<-rp.limitChan
})
task()
}()
}