summaryrefslogtreecommitdiffstats
path: root/src/cmd/go/internal/par/work_test.go
blob: 9d96ffae50ca558db797bd0b4c2d230e767b3faa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package par

import (
	"sync/atomic"
	"testing"
	"time"
)

func TestWork(t *testing.T) {
	var w Work[int]

	const N = 10000
	n := int32(0)
	w.Add(N)
	w.Do(100, func(i int) {
		atomic.AddInt32(&n, 1)
		if i >= 2 {
			w.Add(i - 1)
			w.Add(i - 2)
		}
		w.Add(i >> 1)
		w.Add((i >> 1) ^ 1)
	})
	if n != N+1 {
		t.Fatalf("ran %d items, expected %d", n, N+1)
	}
}

func TestWorkParallel(t *testing.T) {
	for tries := 0; tries < 10; tries++ {
		var w Work[int]
		const N = 100
		for i := 0; i < N; i++ {
			w.Add(i)
		}
		start := time.Now()
		var n int32
		w.Do(N, func(x int) {
			time.Sleep(1 * time.Millisecond)
			atomic.AddInt32(&n, +1)
		})
		if n != N {
			t.Fatalf("par.Work.Do did not do all the work")
		}
		if time.Since(start) < N/2*time.Millisecond {
			return
		}
	}
	t.Fatalf("par.Work.Do does not seem to be parallel")
}

func TestCache(t *testing.T) {
	var cache Cache[int, int]

	n := 1
	v := cache.Do(1, func() int { n++; return n })
	if v != 2 {
		t.Fatalf("cache.Do(1) did not run f")
	}
	v = cache.Do(1, func() int { n++; return n })
	if v != 2 {
		t.Fatalf("cache.Do(1) ran f again!")
	}
	v = cache.Do(2, func() int { n++; return n })
	if v != 3 {
		t.Fatalf("cache.Do(2) did not run f")
	}
	v = cache.Do(1, func() int { n++; return n })
	if v != 2 {
		t.Fatalf("cache.Do(1) did not returned saved value from original cache.Do(1)")
	}
}