github.com/bshelton229/agent@v3.5.4+incompatible/pool/pool.go (about)

     1  package pool
     2  
     3  import (
     4  	"runtime"
     5  	"sync"
     6  )
     7  
     8  type Pool struct {
     9  	wg         *sync.WaitGroup
    10  	completion chan bool
    11  	m          sync.Mutex
    12  }
    13  
    14  const (
    15  	MaxConcurrencyLimit = -1
    16  )
    17  
    18  func New(concurrencyLimit int) *Pool {
    19  	if concurrencyLimit == MaxConcurrencyLimit {
    20  		concurrencyLimit = runtime.NumCPU()
    21  	}
    22  
    23  	wg := sync.WaitGroup{}
    24  	completionChan := make(chan bool, concurrencyLimit)
    25  
    26  	for i := 0; i < concurrencyLimit; i++ {
    27  		completionChan <- true
    28  	}
    29  
    30  	return &Pool{&wg, completionChan, sync.Mutex{}}
    31  }
    32  
    33  func (pool *Pool) Spawn(job func()) {
    34  	<-pool.completion
    35  	pool.wg.Add(1)
    36  
    37  	go func() {
    38  		defer func() {
    39  			pool.completion <- true
    40  			pool.wg.Done()
    41  		}()
    42  
    43  		job()
    44  	}()
    45  }
    46  
    47  func (pool *Pool) Lock() {
    48  	pool.m.Lock()
    49  }
    50  
    51  func (pool *Pool) Unlock() {
    52  	pool.m.Unlock()
    53  }
    54  
    55  func (pool *Pool) Wait() {
    56  	pool.wg.Wait()
    57  }