...

Source file src/cmd/go/internal/par/work_test.go

Documentation: cmd/go/internal/par

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

View as plain text