github.com/gagliardetto/golang-go@v0.0.0-20201020153340-53909ea70814/cmd/go/not-internal/par/work_test.go (about)

     1  // Copyright 2018 The Go 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 par
     6  
     7  import (
     8  	"sync/atomic"
     9  	"testing"
    10  	"time"
    11  )
    12  
    13  func TestWork(t *testing.T) {
    14  	var w Work
    15  
    16  	const N = 10000
    17  	n := int32(0)
    18  	w.Add(N)
    19  	w.Do(100, func(x interface{}) {
    20  		atomic.AddInt32(&n, 1)
    21  		i := x.(int)
    22  		if i >= 2 {
    23  			w.Add(i - 1)
    24  			w.Add(i - 2)
    25  		}
    26  		w.Add(i >> 1)
    27  		w.Add((i >> 1) ^ 1)
    28  	})
    29  	if n != N+1 {
    30  		t.Fatalf("ran %d items, expected %d", n, N+1)
    31  	}
    32  }
    33  
    34  func TestWorkParallel(t *testing.T) {
    35  	for tries := 0; tries < 10; tries++ {
    36  		var w Work
    37  		const N = 100
    38  		for i := 0; i < N; i++ {
    39  			w.Add(i)
    40  		}
    41  		start := time.Now()
    42  		var n int32
    43  		w.Do(N, func(x interface{}) {
    44  			time.Sleep(1 * time.Millisecond)
    45  			atomic.AddInt32(&n, +1)
    46  		})
    47  		if n != N {
    48  			t.Fatalf("par.Work.Do did not do all the work")
    49  		}
    50  		if time.Since(start) < N/2*time.Millisecond {
    51  			return
    52  		}
    53  	}
    54  	t.Fatalf("par.Work.Do does not seem to be parallel")
    55  }
    56  
    57  func TestCache(t *testing.T) {
    58  	var cache Cache
    59  
    60  	n := 1
    61  	v := cache.Do(1, func() interface{} { n++; return n })
    62  	if v != 2 {
    63  		t.Fatalf("cache.Do(1) did not run f")
    64  	}
    65  	v = cache.Do(1, func() interface{} { n++; return n })
    66  	if v != 2 {
    67  		t.Fatalf("cache.Do(1) ran f again!")
    68  	}
    69  	v = cache.Do(2, func() interface{} { n++; return n })
    70  	if v != 3 {
    71  		t.Fatalf("cache.Do(2) did not run f")
    72  	}
    73  	v = cache.Do(1, func() interface{} { n++; return n })
    74  	if v != 2 {
    75  		t.Fatalf("cache.Do(1) did not returned saved value from original cache.Do(1)")
    76  	}
    77  }