1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
17 func TestPool(t
*testing
.T
) {
18 // disable GC so we can control when it happens.
19 defer debug
.SetGCPercent(debug
.SetGCPercent(-1))
22 t
.Fatal("expected empty")
26 if g
:= p
.Get(); g
!= "b" {
27 t
.Fatalf("got %#v; want b", g
)
29 if g
:= p
.Get(); g
!= "a" {
30 t
.Fatalf("got %#v; want a", g
)
32 if g
:= p
.Get(); g
!= nil {
33 t
.Fatalf("got %#v; want nil", g
)
37 debug
.SetGCPercent(100) // to allow following GC to actually run
39 if g
:= p
.Get(); g
!= nil {
40 t
.Fatalf("got %#v; want nil after GC", g
)
44 func TestPoolNew(t
*testing
.T
) {
45 // disable GC so we can control when it happens.
46 defer debug
.SetGCPercent(debug
.SetGCPercent(-1))
50 New
: func() interface{} {
55 if v
:= p
.Get(); v
!= 1 {
56 t
.Fatalf("got %v; want 1", v
)
58 if v
:= p
.Get(); v
!= 2 {
59 t
.Fatalf("got %v; want 2", v
)
62 if v
:= p
.Get(); v
!= 42 {
63 t
.Fatalf("got %v; want 42", v
)
65 if v
:= p
.Get(); v
!= 3 {
66 t
.Fatalf("got %v; want 3", v
)
70 // Test that Pool does not hold pointers to previously cached
72 func TestPoolGC(t
*testing
.T
) {
76 for i
:= 0; i
< N
; i
++ {
78 runtime
.SetFinalizer(v
, func(vv
*int) {
79 atomic
.AddUint32(&fin
, 1)
83 for i
:= 0; i
< N
; i
++ {
86 for i
:= 0; i
< 5; i
++ {
88 time
.Sleep(time
.Millisecond
)
89 // 1 pointer can remain on stack or elsewhere
90 if atomic
.LoadUint32(&fin
) >= N
-1 {
94 // gccgo has a less precise heap.
95 if runtime
.Compiler
== "gccgo" && atomic
.LoadUint32(&fin
) >= N
-5 {
99 t
.Fatalf("only %v out of %v resources are finalized",
100 atomic
.LoadUint32(&fin
), N
)
103 func TestPoolStress(t
*testing
.T
) {
110 done
:= make(chan bool)
111 for i
:= 0; i
< P
; i
++ {
113 var v
interface{} = 0
114 for j
:= 0; j
< N
; j
++ {
120 if v
!= nil && v
.(int) != 0 {
121 t
.Fatalf("expect 0, got %v", v
)
127 for i
:= 0; i
< P
; i
++ {
132 func BenchmarkPool(b
*testing
.B
) {
133 procs
:= runtime
.GOMAXPROCS(-1)
135 if unsafe
.Sizeof(b
.N
) == 8 {
138 return atomic
.AddInt64(&n
, -1) >= 0
143 return atomic
.AddInt32(&n
, -1) >= 0
148 for i
:= 0; i
< procs
; i
++ {