github.com/code-reading/golang@v0.0.0-20220303082512-ba5bc0e589a3/go/src/runtime/race/sched_test.go (about) 1 // Copyright 2015 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 //go:build race 6 // +build race 7 8 package race_test 9 10 import ( 11 "bytes" 12 "fmt" 13 "reflect" 14 "runtime" 15 "testing" 16 ) 17 18 func TestRandomScheduling(t *testing.T) { 19 // Scheduler is most consistent with GOMAXPROCS=1. 20 // Use that to make the test most likely to fail. 21 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) 22 const N = 10 23 out := make([][]int, N) 24 for i := 0; i < N; i++ { 25 c := make(chan int, N) 26 for j := 0; j < N; j++ { 27 go func(j int) { 28 c <- j 29 }(j) 30 } 31 row := make([]int, N) 32 for j := 0; j < N; j++ { 33 row[j] = <-c 34 } 35 out[i] = row 36 } 37 38 for i := 0; i < N; i++ { 39 if !reflect.DeepEqual(out[0], out[i]) { 40 return // found a different order 41 } 42 } 43 44 var buf bytes.Buffer 45 for i := 0; i < N; i++ { 46 fmt.Fprintf(&buf, "%v\n", out[i]) 47 } 48 t.Fatalf("consistent goroutine execution order:\n%v", buf.String()) 49 }