go-hep.org/x/hep@v0.38.1/fwk/utils/parallel/parallel_test.go (about)

     1  // Copyright ©2017 The go-hep 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 parallel_test
     6  
     7  import (
     8  	"sort"
     9  	"sync"
    10  	"testing"
    11  	"time"
    12  
    13  	"go-hep.org/x/hep/fwk/utils/parallel"
    14  )
    15  
    16  func TestParallelMaxPar(t *testing.T) {
    17  	const (
    18  		totalDo = 10
    19  		maxPar  = 3
    20  	)
    21  	var mu sync.Mutex
    22  	max := 0
    23  	n := 0
    24  	tot := 0
    25  	r := parallel.NewRun(maxPar)
    26  	for range totalDo {
    27  		r.Do(func() error {
    28  			mu.Lock()
    29  			tot++
    30  			n++
    31  			if n > max {
    32  				max = n
    33  			}
    34  			mu.Unlock()
    35  			time.Sleep(0.1e9)
    36  			mu.Lock()
    37  			n--
    38  			mu.Unlock()
    39  			return nil
    40  		})
    41  	}
    42  	err := r.Wait()
    43  	if n != 0 {
    44  		t.Errorf("%d functions still running", n)
    45  	}
    46  	if tot != totalDo {
    47  		t.Errorf("all functions not executed; want %d got %d", totalDo, tot)
    48  	}
    49  	if err != nil {
    50  		t.Errorf("wrong error; want nil got %v", err)
    51  	}
    52  	if max != maxPar {
    53  		t.Errorf("wrong number of do's ran at once; want %d got %d", maxPar, max)
    54  	}
    55  }
    56  
    57  type intError int
    58  
    59  func (intError) Error() string {
    60  	return "error"
    61  }
    62  
    63  func TestParallelError(t *testing.T) {
    64  	const (
    65  		totalDo = 10
    66  		errDo   = 5
    67  	)
    68  	r := parallel.NewRun(6)
    69  	for i := range totalDo {
    70  		i := i
    71  		if i >= errDo {
    72  			r.Do(func() error {
    73  				return intError(i)
    74  			})
    75  		} else {
    76  			r.Do(func() error {
    77  				return nil
    78  			})
    79  		}
    80  	}
    81  	err := r.Wait()
    82  	if err == nil {
    83  		t.Fatalf("expected error, got none")
    84  	}
    85  	errs := err.(parallel.Errors)
    86  	if len(errs) != totalDo-errDo {
    87  		t.Fatalf("wrong error count; want %d got %d", len(errs), totalDo-errDo)
    88  	}
    89  	ints := make([]int, len(errs))
    90  	for i, err := range errs {
    91  		ints[i] = int(err.(intError))
    92  	}
    93  	sort.Ints(ints)
    94  	for i, n := range ints {
    95  		if n != i+errDo {
    96  			t.Errorf("unexpected error value; want %d got %d", i+errDo, n)
    97  		}
    98  	}
    99  }