github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/goroutines.go (about)

     1  package f
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/panjf2000/ants/v2"
     6  	"sync"
     7  )
     8  
     9  // GoPool ants.Pool
    10  type GoPool struct {
    11  	*ants.Pool
    12  }
    13  
    14  // GoHandle a Simple Goroutines Pool
    15  var GoHandle *GoPool
    16  
    17  func init() {
    18  	defaultPool, _ := ants.NewPool(ants.DefaultAntsPoolSize, ants.WithOptions(ants.Options{
    19  		ExpiryDuration:   ants.DefaultCleanIntervalTime,
    20  		PreAlloc:         false,
    21  		Nonblocking:      true,
    22  		MaxBlockingTasks: 0,
    23  		PanicHandler: func(err interface{}) {
    24  			_ = fmt.Errorf(" GoHandle/worker: %s\n %v", Now().LocalTimeString(), err)
    25  		},
    26  	}))
    27  	GoHandle = &GoPool{Pool: defaultPool}
    28  }
    29  
    30  // GoWithFunc Create a ants.PoolWithFunc.
    31  func GoWithFunc(size int, pf func(interface{}), options ...ants.Option) (*GoPoolWithFunc, error) {
    32  	pool, err := ants.NewPoolWithFunc(size, pf, options...)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	return &GoPoolWithFunc{PoolWithFunc: pool}, nil
    37  }
    38  
    39  // GoTimes Create a ants.PoolWithFunc.
    40  func GoTimes(n int, fn func(i int), options ...ants.Option) error {
    41  	var size int
    42  	if n < 100 {
    43  		size = 10
    44  	} else if n < 1000 {
    45  		size = 100
    46  	} else if n < 10000 {
    47  		size = 1000
    48  	} else {
    49  		size = 2000
    50  	}
    51  
    52  	var wg sync.WaitGroup
    53  	pool, err := ants.NewPoolWithFunc(size, func(i interface{}) {
    54  		fn(i.(int))
    55  		wg.Done()
    56  	}, options...)
    57  	if err != nil {
    58  		return err
    59  	}
    60  
    61  	p := &GoPoolWithFunc{PoolWithFunc: pool}
    62  	defer p.Release()
    63  	for i := 0; i < n; i++ {
    64  		wg.Add(1)
    65  		_ = p.Invoke(i)
    66  	}
    67  	wg.Wait()
    68  	return nil
    69  }