github.com/sykesm/fabric@v1.1.0-preview.0.20200129034918-2aa12b1a0181/core/ledger/kvledger/txmgmt/statedb/statecouchdb/batch_util.go (about)

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