github.com/aclements/go-misc@v0.0.0-20240129233631-2f6ede80790c/go-weave/weave/waitgroup.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package weave
     6  
     7  type WaitGroup struct {
     8  	n       int
     9  	waiters []*thread
    10  }
    11  
    12  func (g *WaitGroup) Add(delta int) {
    13  	g.n += delta
    14  	if g.n == 0 {
    15  		waiters := g.waiters
    16  		g.waiters = nil
    17  		for _, t := range waiters {
    18  			t.unblock()
    19  		}
    20  	}
    21  }
    22  
    23  func (g *WaitGroup) Done() {
    24  	g.Add(-1)
    25  }
    26  
    27  func (g *WaitGroup) Wait() {
    28  	if g.n == 0 {
    29  		globalSched.Sched()
    30  		return
    31  	}
    32  	this := globalSched.curThread
    33  	g.waiters = append(g.waiters, this)
    34  	this.block(g.reset)
    35  }
    36  
    37  func (g *WaitGroup) reset() {
    38  	*g = WaitGroup{}
    39  }