Russ Cox | d2cc988 | 2012-02-16 23:50:37 -0500 | [diff] [blame] | 1 | // run |
Russ Cox | 507df95 | 2011-04-13 23:42:06 -0400 | [diff] [blame] | 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 | |
Rob Pike | 83976e3 | 2012-02-19 14:28:53 +1100 | [diff] [blame] | 7 | // Test that buffered channels are garbage collected properly. |
Russ Cox | 507df95 | 2011-04-13 23:42:06 -0400 | [diff] [blame] | 8 | // An interesting case because they have finalizers and used to |
| 9 | // have self loops that kept them from being collected. |
| 10 | // (Cyclic data with finalizers is never finalized, nor collected.) |
| 11 | |
| 12 | package main |
| 13 | |
| 14 | import ( |
| 15 | "fmt" |
| 16 | "os" |
| 17 | "runtime" |
| 18 | ) |
| 19 | |
| 20 | func main() { |
| 21 | const N = 10000 |
Rémy Oudompheng | 842c906 | 2012-02-06 19:16:26 +0100 | [diff] [blame] | 22 | st := new(runtime.MemStats) |
| 23 | memstats := new(runtime.MemStats) |
| 24 | runtime.ReadMemStats(st) |
Russ Cox | 507df95 | 2011-04-13 23:42:06 -0400 | [diff] [blame] | 25 | for i := 0; i < N; i++ { |
| 26 | c := make(chan int, 10) |
| 27 | _ = c |
| 28 | if i%100 == 0 { |
| 29 | for j := 0; j < 4; j++ { |
| 30 | runtime.GC() |
| 31 | runtime.Gosched() |
| 32 | runtime.GC() |
| 33 | runtime.Gosched() |
| 34 | } |
| 35 | } |
| 36 | } |
Russ Cox | 226fb09 | 2011-07-22 00:55:01 -0400 | [diff] [blame] | 37 | |
Rémy Oudompheng | 842c906 | 2012-02-06 19:16:26 +0100 | [diff] [blame] | 38 | runtime.ReadMemStats(memstats) |
| 39 | obj := memstats.HeapObjects - st.HeapObjects |
Russ Cox | 507df95 | 2011-04-13 23:42:06 -0400 | [diff] [blame] | 40 | if obj > N/5 { |
| 41 | fmt.Println("too many objects left:", obj) |
| 42 | os.Exit(1) |
| 43 | } |
| 44 | } |