github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/core/ledger/kvledger/txmgmt/statedb/statecouchdb/batch_util.go (about)

     1  /*
     2  Copyright hechain. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package statecouchdb
     8  
     9  import (
    10  	"sync"
    11  
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  // batch is executed in a separate goroutine.
    16  type batch interface {
    17  	execute() error
    18  }
    19  
    20  // executeBatches executes each batch in a separate goroutine and returns error if
    21  // any of the batches return error during its execution
    22  func executeBatches(batches []batch) error {
    23  	logger.Debugf("Executing batches = %s", batches)
    24  	numBatches := len(batches)
    25  	if numBatches == 0 {
    26  		return nil
    27  	}
    28  	if numBatches == 1 {
    29  		return batches[0].execute()
    30  	}
    31  	var batchWG sync.WaitGroup
    32  	batchWG.Add(numBatches)
    33  	errsChan := make(chan error, numBatches)
    34  	defer close(errsChan)
    35  	for _, b := range batches {
    36  		go func(b batch) {
    37  			defer batchWG.Done()
    38  			if err := b.execute(); err != nil {
    39  				errsChan <- err
    40  			}
    41  		}(b)
    42  	}
    43  	batchWG.Wait()
    44  
    45  	select {
    46  	case err := <-errsChan:
    47  		return errors.WithStack(err)
    48  	default:
    49  		return nil
    50  	}
    51  }