github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/util/waitgroup/waitgroup.go (about)

     1  /*
     2  Copyright 2017 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package waitgroup
    18  
    19  import (
    20  	"fmt"
    21  	"sync"
    22  )
    23  
    24  // SafeWaitGroup must not be copied after first use.
    25  type SafeWaitGroup struct {
    26  	wg sync.WaitGroup
    27  	mu sync.RWMutex
    28  	// wait indicate whether Wait is called, if true,
    29  	// then any Add with positive delta will return error.
    30  	wait bool
    31  }
    32  
    33  // Add adds delta, which may be negative, similar to sync.WaitGroup.
    34  // If Add with a positive delta happens after Wait, it will return error,
    35  // which prevent unsafe Add.
    36  func (wg *SafeWaitGroup) Add(delta int) error {
    37  	wg.mu.RLock()
    38  	defer wg.mu.RUnlock()
    39  	if wg.wait && delta > 0 {
    40  		return fmt.Errorf("add with positive delta after Wait is forbidden")
    41  	}
    42  	wg.wg.Add(delta)
    43  	return nil
    44  }
    45  
    46  // Done decrements the WaitGroup counter.
    47  func (wg *SafeWaitGroup) Done() {
    48  	wg.wg.Done()
    49  }
    50  
    51  // Wait blocks until the WaitGroup counter is zero.
    52  func (wg *SafeWaitGroup) Wait() {
    53  	wg.mu.Lock()
    54  	wg.wait = true
    55  	wg.mu.Unlock()
    56  	wg.wg.Wait()
    57  }