2020-12-09 09:47:24 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
// WorkerContext 上下文
|
|
|
|
type WorkerContext struct {
|
|
|
|
wg *sync.WaitGroup
|
|
|
|
}
|
|
|
|
|
|
|
|
// Done 必须在Handler里结束时处理. 默认defer cxt.Done()
|
|
|
|
func (cxt *WorkerContext) Done() {
|
|
|
|
cxt.wg.Done()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Worker 主进程
|
|
|
|
type Worker struct {
|
|
|
|
cxt *WorkerContext
|
|
|
|
}
|
|
|
|
|
|
|
|
var worker = func() *Worker {
|
|
|
|
w := &Worker{}
|
|
|
|
w.cxt = &WorkerContext{}
|
2020-12-09 10:11:52 +00:00
|
|
|
w.cxt.wg = &sync.WaitGroup{}
|
2020-12-09 09:47:24 +00:00
|
|
|
return w
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Handler 处理方法
|
|
|
|
func (w *Worker) Handler(handleFunc func(cxt *WorkerContext)) {
|
2020-12-09 10:11:52 +00:00
|
|
|
w.cxt.wg.Add(1)
|
2020-12-09 09:47:24 +00:00
|
|
|
go handleFunc(w.cxt)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run 运行
|
|
|
|
func (w *Worker) Run() {
|
|
|
|
log.Println("worker running")
|
2020-12-09 10:11:52 +00:00
|
|
|
w.cxt.wg.Wait()
|
2020-12-09 09:47:24 +00:00
|
|
|
log.Println("worker stop")
|
|
|
|
}
|