github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/mq/worker/worker.go (about)

     1  package worker
     2  
     3  import (
     4  	"context"
     5  	"sync"
     6  )
     7  
     8  func New(proc func(ctx context.Context) error, num int) *Worker {
     9  	return &Worker{num: num, proc: proc}
    10  }
    11  
    12  type Worker struct {
    13  	num  int
    14  	proc func(ctx context.Context) error
    15  	wg   sync.WaitGroup
    16  }
    17  
    18  func (w *Worker) Start(ctx context.Context) {
    19  	w.wg.Add(w.num)
    20  
    21  	for i := 0; i < w.num; i++ {
    22  		go func() {
    23  			defer w.wg.Done()
    24  
    25  			for {
    26  				select {
    27  				case <-ctx.Done():
    28  					return
    29  				default:
    30  					w.proc(ctx)
    31  				}
    32  			}
    33  		}()
    34  	}
    35  
    36  	w.wg.Wait()
    37  }