summaryrefslogtreecommitdiffstats
path: root/src/internal/trace/v2/testdata/testprog/futile-wakeup.go
blob: cc489818fc9fcb5bf98d15b705198c0450bff15f (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
77
78
79
80
81
82
83
84
// Copyright 2023 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.

// Tests to make sure the runtime doesn't generate futile wakeups. For example,
// it makes sure that a block on a channel send that unblocks briefly only to
// immediately go back to sleep (in such a way that doesn't reveal any useful
// information, and is purely an artifact of the runtime implementation) doesn't
// make it into the trace.

//go:build ignore

package main

import (
	"context"
	"log"
	"os"
	"runtime"
	"runtime/trace"
	"sync"
)

func main() {
	if err := trace.Start(os.Stdout); err != nil {
		log.Fatalf("failed to start tracing: %v", err)
	}

	defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(8))
	c0 := make(chan int, 1)
	c1 := make(chan int, 1)
	c2 := make(chan int, 1)
	const procs = 2
	var done sync.WaitGroup
	done.Add(4 * procs)
	for p := 0; p < procs; p++ {
		const iters = 1e3
		go func() {
			trace.WithRegion(context.Background(), "special", func() {
				for i := 0; i < iters; i++ {
					runtime.Gosched()
					c0 <- 0
				}
				done.Done()
			})
		}()
		go func() {
			trace.WithRegion(context.Background(), "special", func() {
				for i := 0; i < iters; i++ {
					runtime.Gosched()
					<-c0
				}
				done.Done()
			})
		}()
		go func() {
			trace.WithRegion(context.Background(), "special", func() {
				for i := 0; i < iters; i++ {
					runtime.Gosched()
					select {
					case c1 <- 0:
					case c2 <- 0:
					}
				}
				done.Done()
			})
		}()
		go func() {
			trace.WithRegion(context.Background(), "special", func() {
				for i := 0; i < iters; i++ {
					runtime.Gosched()
					select {
					case <-c1:
					case <-c2:
					}
				}
				done.Done()
			})
		}()
	}
	done.Wait()

	trace.Stop()
}