40 lines
587 B
Go
40 lines
587 B
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"sync"
|
|
)
|
|
|
|
// WorkerContext 上下文
|
|
type WorkerContext struct {
|
|
wg *sync.WaitGroup
|
|
}
|
|
|
|
// Worker 主进程
|
|
type Worker struct {
|
|
cxt *WorkerContext
|
|
}
|
|
|
|
var worker = func() *Worker {
|
|
w := &Worker{}
|
|
w.cxt = &WorkerContext{}
|
|
w.cxt.wg = &sync.WaitGroup{}
|
|
return w
|
|
}()
|
|
|
|
// Handler 处理方法
|
|
func (w *Worker) Handler(handleFunc func(cxt *WorkerContext)) {
|
|
w.cxt.wg.Add(1)
|
|
go func() {
|
|
defer w.cxt.wg.Done()
|
|
handleFunc(w.cxt)
|
|
}()
|
|
}
|
|
|
|
// Run 运行
|
|
func (w *Worker) Run() {
|
|
log.Println("worker running")
|
|
w.cxt.wg.Wait()
|
|
log.Println("worker stop")
|
|
}
|