Source file
test/stackobj.go
1
2
3
4
5
6
7 package main
8
9 import (
10 "fmt"
11 "runtime"
12 )
13
14 type HeapObj [8]int64
15
16 type StkObj struct {
17 h *HeapObj
18 }
19
20 var n int
21 var c int = -1
22
23 func gc() {
24
25 runtime.GC()
26 runtime.GC()
27 runtime.GC()
28 n++
29 }
30
31 func main() {
32 f()
33 gc()
34 if c < 0 {
35 panic("heap object never collected")
36 }
37 if c != 1 {
38 panic(fmt.Sprintf("expected collection at phase 1, got phase %d", c))
39 }
40 }
41
42 func f() {
43 var s StkObj
44 s.h = new(HeapObj)
45 runtime.SetFinalizer(s.h, func(h *HeapObj) {
46
47 c = n
48 })
49 g(&s)
50 gc()
51 }
52
53 func g(s *StkObj) {
54 gc()
55 runtime.KeepAlive(s)
56 gc()
57 }
58
View as plain text