github.com/netdata/go.d.plugin@v0.58.1/modules/vsphere/scrape/throttled_caller.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package scrape
     4  
     5  import "sync"
     6  
     7  type throttledCaller struct {
     8  	limit chan struct{}
     9  	wg    sync.WaitGroup
    10  }
    11  
    12  func newThrottledCaller(limit int) *throttledCaller {
    13  	if limit <= 0 {
    14  		panic("limit must be > 0")
    15  	}
    16  	return &throttledCaller{limit: make(chan struct{}, limit)}
    17  }
    18  
    19  func (t *throttledCaller) call(job func()) {
    20  	t.wg.Add(1)
    21  	go func() {
    22  		defer t.wg.Done()
    23  		t.limit <- struct{}{}
    24  		defer func() {
    25  			<-t.limit
    26  		}()
    27  		job()
    28  	}()
    29  }
    30  
    31  func (t *throttledCaller) wait() {
    32  	t.wg.Wait()
    33  }