blob: 2f8eb9b70e66fdac06c40bf2dba4ccbdb27f78a3 [file] [log] [blame]
Richard Musiole3c68472018-03-04 12:15:37 +01001// +build !nacl,!js
Rahul Chaudhry8581d482015-02-03 10:52:18 -08002// run
Russ Cox0c2a7272014-05-20 12:10:19 -04003
Emmanuel Odeke53fd5222016-04-10 14:32:26 -07004// Copyright 2011 The Go Authors. All rights reserved.
Russ Cox507df952011-04-13 23:42:06 -04005// Use of this source code is governed by a BSD-style
6// license that can be found in the LICENSE file.
7
Rob Pike83976e32012-02-19 14:28:53 +11008// Test that buffered channels are garbage collected properly.
Russ Cox507df952011-04-13 23:42:06 -04009// An interesting case because they have finalizers and used to
10// have self loops that kept them from being collected.
11// (Cyclic data with finalizers is never finalized, nor collected.)
12
13package main
14
15import (
16 "fmt"
17 "os"
18 "runtime"
19)
20
21func main() {
22 const N = 10000
Rémy Oudompheng842c9062012-02-06 19:16:26 +010023 st := new(runtime.MemStats)
24 memstats := new(runtime.MemStats)
25 runtime.ReadMemStats(st)
Russ Cox507df952011-04-13 23:42:06 -040026 for i := 0; i < N; i++ {
27 c := make(chan int, 10)
28 _ = c
29 if i%100 == 0 {
30 for j := 0; j < 4; j++ {
31 runtime.GC()
32 runtime.Gosched()
33 runtime.GC()
34 runtime.Gosched()
35 }
36 }
37 }
Russ Cox226fb092011-07-22 00:55:01 -040038
Rémy Oudompheng842c9062012-02-06 19:16:26 +010039 runtime.ReadMemStats(memstats)
Russ Cox0c2a7272014-05-20 12:10:19 -040040 obj := int64(memstats.HeapObjects - st.HeapObjects)
Russ Cox507df952011-04-13 23:42:06 -040041 if obj > N/5 {
42 fmt.Println("too many objects left:", obj)
43 os.Exit(1)
44 }
45}