Debian Codegraph @

test/init1.go

raw
1 // run
2
3 // Copyright 2011 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 // Test that goroutines and garbage collection run during init.
8
9 package main
10
11 import "runtime"
12
13 var x []byte
14
15 func init() {
16 c := make(chan int)
17 go send(c)
18 <-c
19
20 const N = 1000
21 const MB = 1 << 20
22 b := make([]byte, MB)
23 for i := range b {
24 b[i] = byte(i%10 + '0')
25 }
26 s := string(b)
27
28 memstats := new(runtime.MemStats)
29 runtime.ReadMemStats(memstats)
30 sys, numGC := memstats.Sys, memstats.NumGC
31
32 // Generate 1,000 MB of garbage, only retaining 1 MB total.
33 for i := 0; i < N; i++ {
34 x = []byte(s)
35 }
36
37 // Verify that the garbage collector ran by seeing if we
38 // allocated fewer than N*MB bytes from the system.
39 runtime.ReadMemStats(memstats)
40 sys1, numGC1 := memstats.Sys, memstats.NumGC
41 if sys1-sys >= N*MB || numGC1 == numGC {
42 println("allocated 1000 chunks of", MB, "and used ", sys1-sys, "memory")
43 println("numGC went", numGC, "to", numGC1)
44 panic("init1")
45 }
46 }
47
48 func send(c chan int) {
49 c <- 1
50 }
51
52 func main() {
53 }