Russ Cox | 33e396a | 2010-02-03 16:31:34 -0800 | [diff] [blame] | 1 | // $G $D/$F.go && $L $F.$A && ./$A.out |
| 2 | |
| 3 | // Copyright 2009 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 | // trivial finalizer test |
| 8 | |
| 9 | package main |
| 10 | |
Russ Cox | 4e28cfe | 2010-03-26 14:15:30 -0700 | [diff] [blame] | 11 | import ( |
| 12 | "runtime" |
| 13 | "time" |
| 14 | ) |
Russ Cox | 33e396a | 2010-02-03 16:31:34 -0800 | [diff] [blame] | 15 | |
| 16 | const N = 250 |
| 17 | |
| 18 | type A struct { |
| 19 | b *B |
| 20 | n int |
| 21 | } |
| 22 | |
| 23 | type B struct { |
| 24 | n int |
| 25 | } |
| 26 | |
| 27 | var i int |
| 28 | var nfinal int |
| 29 | var final [N]int |
| 30 | |
Russ Cox | 4e28cfe | 2010-03-26 14:15:30 -0700 | [diff] [blame] | 31 | // the unused return is to test finalizers with return values |
| 32 | func finalA(a *A) (unused [N]int) { |
Russ Cox | 33e396a | 2010-02-03 16:31:34 -0800 | [diff] [blame] | 33 | if final[a.n] != 0 { |
Rob Pike | 325cf8e | 2010-03-24 16:46:53 -0700 | [diff] [blame] | 34 | println("finalA", a.n, final[a.n]) |
| 35 | panic("fail") |
Russ Cox | 33e396a | 2010-02-03 16:31:34 -0800 | [diff] [blame] | 36 | } |
| 37 | final[a.n] = 1 |
Russ Cox | 4e28cfe | 2010-03-26 14:15:30 -0700 | [diff] [blame] | 38 | return |
Russ Cox | 33e396a | 2010-02-03 16:31:34 -0800 | [diff] [blame] | 39 | } |
| 40 | |
| 41 | func finalB(b *B) { |
| 42 | if final[b.n] != 1 { |
Rob Pike | 325cf8e | 2010-03-24 16:46:53 -0700 | [diff] [blame] | 43 | println("finalB", b.n, final[b.n]) |
| 44 | panic("fail") |
Russ Cox | 33e396a | 2010-02-03 16:31:34 -0800 | [diff] [blame] | 45 | } |
| 46 | final[b.n] = 2 |
| 47 | nfinal++ |
| 48 | } |
| 49 | |
| 50 | func main() { |
| 51 | runtime.GOMAXPROCS(4) |
| 52 | for i = 0; i < N; i++ { |
| 53 | b := &B{i} |
| 54 | a := &A{b, i} |
| 55 | runtime.SetFinalizer(b, finalB) |
| 56 | runtime.SetFinalizer(a, finalA) |
| 57 | } |
| 58 | for i := 0; i < N; i++ { |
| 59 | runtime.GC() |
| 60 | runtime.Gosched() |
Russ Cox | 00f9f0c | 2010-03-30 10:34:57 -0700 | [diff] [blame] | 61 | time.Sleep(1e6) |
Russ Cox | 33e396a | 2010-02-03 16:31:34 -0800 | [diff] [blame] | 62 | } |
Russ Cox | a00917c | 2010-03-24 19:52:07 -0700 | [diff] [blame] | 63 | if nfinal < N*8/10 { |
Russ Cox | 00f9f0c | 2010-03-30 10:34:57 -0700 | [diff] [blame] | 64 | println("not enough finalizing:", nfinal, "/", N) |
| 65 | panic("fail") |
Russ Cox | 33e396a | 2010-02-03 16:31:34 -0800 | [diff] [blame] | 66 | } |
| 67 | } |