github.com/pubgo/xprocess@v0.1.11/xprocess_group/group.go (about)

     1  package xprocess_group
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/pubgo/xerror"
     7  	"github.com/pubgo/xlog"
     8  	"github.com/pubgo/xprocess/xprocess_waitgroup"
     9  	"go.uber.org/zap"
    10  )
    11  
    12  type Group = group
    13  type group struct {
    14  	ctx    context.Context
    15  	cancel context.CancelFunc
    16  	wg     xprocess_waitgroup.WaitGroup
    17  }
    18  
    19  // New
    20  // 创建一个group对象, 可以带上默认的Context
    21  func New(c ...uint16) *group {
    22  	ctx, cancel := context.WithCancel(context.Background())
    23  	g := &group{ctx: ctx, cancel: cancel, wg: xprocess_waitgroup.New(true, c...)}
    24  	return g
    25  }
    26  
    27  // Cancel
    28  // 停止正在运行的函数
    29  func (g *group) Cancel() { g.cancel() }
    30  
    31  // Count
    32  // 当前的goroutine数量
    33  func (g *group) Count() uint16 { return g.wg.Count() }
    34  
    35  // Wait
    36  // 等待正在运行的函数
    37  func (g *group) Wait() { g.wg.Wait(); g.cancel() }
    38  
    39  // Go
    40  // 运行一个goroutine
    41  func (g *group) Go(fn func(ctx context.Context)) {
    42  	xerror.Assert(fn == nil, "[fn] should not be nil")
    43  
    44  	g.wg.Inc()
    45  	go func() {
    46  		defer g.wg.Done()
    47  		defer xerror.Resp(func(err xerror.XErr) { xlog.Error("group.Go error", zap.Any("err", err)) })
    48  		fn(g.ctx)
    49  	}()
    50  }