github.com/yanyiwu/go@v0.0.0-20150106053140-03d6637dbb7f/test/init1.go (about)

     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 chunk = 1 << 20
    21  	memstats := new(runtime.MemStats)
    22  	runtime.ReadMemStats(memstats)
    23  	sys := memstats.Sys
    24  	b := make([]byte, chunk)
    25  	for i := range b {
    26  		b[i] = byte(i%10 + '0')
    27  	}
    28  	s := string(b)
    29  	for i := 0; i < 1000; i++ {
    30  		x = []byte(s)
    31  	}
    32  	runtime.ReadMemStats(memstats)
    33  	sys1 := memstats.Sys
    34  	if sys1-sys > chunk*50 {
    35  		println("allocated 1000 chunks of", chunk, "and used ", sys1-sys, "memory")
    36  		panic("init1")
    37  	}
    38  }
    39  
    40  func send(c chan int) {
    41  	c <- 1
    42  }
    43  
    44  func main() {
    45  }