github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/concurrent/concurrent.go (about)

     1  package concurrent
     2  
     3  import (
     4  	"context"
     5  
     6  	"golang.org/x/sync/errgroup"
     7  )
     8  
     9  type Concurrent struct {
    10  	group       *errgroup.Group
    11  	panicHandle func(x interface{})
    12  }
    13  
    14  func (c *Concurrent) SpawnContext(ctx context.Context, fn func(ctx context.Context) error) {
    15  	c.group.Go(func() error {
    16  		defer func() {
    17  			if x := recover(); x != nil {
    18  				if c.panicHandle != nil {
    19  					c.panicHandle(x)
    20  				}
    21  			}
    22  		}()
    23  		return fn(ctx)
    24  	})
    25  }
    26  
    27  func (c *Concurrent) Spawn(fn func() error) {
    28  	c.group.Go(func() error {
    29  		defer func() {
    30  			if x := recover(); x != nil {
    31  				if c.panicHandle != nil {
    32  					c.panicHandle(x)
    33  				}
    34  			}
    35  		}()
    36  		return fn()
    37  	})
    38  }
    39  
    40  func (c *Concurrent) Wait(ctx context.Context) error {
    41  	return c.group.Wait()
    42  }
    43  
    44  func (c *Concurrent) SpawnAndWait(ctx context.Context, fns ...func(context.Context) error) error {
    45  	for _, fn := range fns {
    46  		c.SpawnContext(ctx, fn)
    47  	}
    48  	return c.Wait(ctx)
    49  }
    50  
    51  func NewConcurrent(ctx context.Context) (*Concurrent, context.Context) {
    52  	group, ctx := errgroup.WithContext(ctx)
    53  	return &Concurrent{group: group}, ctx
    54  }