External

Group

tools.svg
Group 用于并发的执行一组 actor,每个 actor 有两个方法,如下:

  1. type actor struct {
  2. execute func() error
  3. interrupt func(error)
  4. }

执行过程如下所示,需要注意的是,因为每个 actor 必然返回 error 或 nil,因此,接受错误的 chan 会在第一个执行完成的 actor 返回后触发。

  1. func (g *Group) Run() error {
  2. if len(g.actors) == 0 {
  3. return nil
  4. }
  5. // Run each actor.
  6. errors := make(chan error, len(g.actors))
  7. for _, a := range g.actors {
  8. go func(a actor) {
  9. errors <- a.execute()
  10. }(a)
  11. }
  12. // Wait for the first actor to stop.
  13. err := <-errors
  14. // Signal all actors to stop.
  15. for _, a := range g.actors {
  16. a.interrupt(err)
  17. }
  18. // Wait for all actors to stop.
  19. for i := 1; i < cap(errors); i++ {
  20. <-errors
  21. }
  22. // Return the original error.
  23. return err
  24. }

分析:根据 Group 的设计,一个任务执行出错或执行完成后,其他任务都要停止运行,方便管理系统中的核心任