github.com/haraldrudell/parl@v0.4.176/wait-group.go (about)

     1  /*
     2  © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  import (
     9  	"fmt"
    10  	"sync"
    11  )
    12  
    13  // parl.WaitGroup is like a sync.Waitgroup that can be inspected.
    14  // The Waiting method returns the number of threads waited for.
    15  // parl.WaitGroup requires no initialization.
    16  //
    17  //	var wg parl.WaitGroup
    18  //	wg.Add(1)
    19  //	…
    20  //	wg.Waiting()
    21  type WaitGroup struct {
    22  	sync.WaitGroup // Wait()
    23  	lock           sync.Mutex
    24  	adds           int
    25  	dones          int
    26  }
    27  
    28  func NewWaitGroup() (waitGroup *WaitGroup) {
    29  	return &WaitGroup{}
    30  }
    31  
    32  func (wg *WaitGroup) Add(delta int) {
    33  	wg.lock.Lock()
    34  	defer wg.lock.Unlock()
    35  
    36  	wg.adds += delta
    37  	wg.WaitGroup.Add(delta)
    38  }
    39  
    40  func (wg *WaitGroup) Done() {
    41  	wg.DoneBool()
    42  }
    43  
    44  func (wg *WaitGroup) DoneBool() (isExit bool) {
    45  	wg.lock.Lock()
    46  	defer wg.lock.Unlock()
    47  
    48  	wg.dones++
    49  	wg.WaitGroup.Done()
    50  	return wg.dones == wg.adds
    51  }
    52  
    53  func (wg *WaitGroup) Count() (remaining int) {
    54  	adds, dones := wg.Counters()
    55  	remaining = adds - dones
    56  	return
    57  }
    58  
    59  func (wg *WaitGroup) Counters() (adds int, dones int) {
    60  	wg.lock.Lock()
    61  	defer wg.lock.Unlock()
    62  
    63  	adds = wg.adds
    64  	dones = wg.dones
    65  	return
    66  }
    67  
    68  func (wg *WaitGroup) IsZero() (isZero bool) {
    69  	adds, dones := wg.Counters()
    70  	return adds == dones
    71  }
    72  
    73  func (wg *WaitGroup) String() (s string) {
    74  	adds, dones := wg.Counters()
    75  	return fmt.Sprintf("%d(%d)", adds-dones, adds)
    76  }