vitess.io/vitess@v0.16.2/go/vt/mysqlctl/utils.go (about)

     1  /*
     2  Copyright 2019 The Vitess 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 mysqlctl
    18  
    19  import (
    20  	"vitess.io/vitess/go/vt/log"
    21  )
    22  
    23  type MapFunc func(index int) error
    24  
    25  // ConcurrentMap applies fun in a concurrent manner on integers from 0
    26  // to n-1 (they are assumed to be indexes of some slice containing
    27  // items to be processed). The first error returned by a fun
    28  // application will returned (subsequent errors will only be
    29  // logged). It will use concurrency goroutines.
    30  func ConcurrentMap(concurrency, n int, fun MapFunc) error {
    31  	errors := make(chan error)
    32  	work := make(chan int, n)
    33  
    34  	for i := 0; i < n; i++ {
    35  		work <- i
    36  	}
    37  	close(work)
    38  
    39  	for j := 0; j < concurrency; j++ {
    40  		go func() {
    41  			for i := range work {
    42  				errors <- fun(i)
    43  			}
    44  		}()
    45  	}
    46  	var err error
    47  
    48  	for i := 0; i < n; i++ {
    49  		if e := <-errors; e != nil {
    50  			if err != nil {
    51  				log.Errorf("multiple errors, this one happened but it won't be returned: %v", err)
    52  			}
    53  			err = e
    54  		}
    55  	}
    56  	return err
    57  }