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.
5 // Pool is no-op under race detector, so all these tests do not work.
19 func TestPool(t
*testing
.T
) {
20 // disable GC so we can control when it happens.
21 defer debug
.SetGCPercent(debug
.SetGCPercent(-1))
24 t
.Fatal("expected empty")
27 // Make sure that the goroutine doesn't migrate to another P
28 // between Put and Get calls.
32 if g
:= p
.Get(); g
!= "a" {
33 t
.Fatalf("got %#v; want a", g
)
35 if g
:= p
.Get(); g
!= "b" {
36 t
.Fatalf("got %#v; want b", g
)
38 if g
:= p
.Get(); g
!= nil {
39 t
.Fatalf("got %#v; want nil", g
)
44 debug
.SetGCPercent(100) // to allow following GC to actually run
46 if g
:= p
.Get(); g
!= nil {
47 t
.Fatalf("got %#v; want nil after GC", g
)
51 func TestPoolNew(t
*testing
.T
) {
52 // disable GC so we can control when it happens.
53 defer debug
.SetGCPercent(debug
.SetGCPercent(-1))
57 New
: func() interface{} {
62 if v
:= p
.Get(); v
!= 1 {
63 t
.Fatalf("got %v; want 1", v
)
65 if v
:= p
.Get(); v
!= 2 {
66 t
.Fatalf("got %v; want 2", v
)
69 // Make sure that the goroutine doesn't migrate to another P
70 // between Put and Get calls.
73 if v
:= p
.Get(); v
!= 42 {
74 t
.Fatalf("got %v; want 42", v
)
78 if v
:= p
.Get(); v
!= 3 {
79 t
.Fatalf("got %v; want 3", v
)
83 // Test that Pool does not hold pointers to previously cached resources.
84 func TestPoolGC(t
*testing
.T
) {
88 // Test that Pool releases resources on GC.
89 func TestPoolRelease(t
*testing
.T
) {
93 func testPool(t
*testing
.T
, drain
bool) {
94 t
.Skip("gccgo imprecise GC breaks this test")
98 for try
:= 0; try
< 3; try
++ {
100 for i
:= 0; i
< N
; i
++ {
102 runtime
.SetFinalizer(v
, func(vv
*string) {
103 atomic
.AddUint32(&fin
, 1)
108 for i
:= 0; i
< N
; i
++ {
112 for i
:= 0; i
< 5; i
++ {
114 time
.Sleep(time
.Duration(i
*100+10) * time
.Millisecond
)
115 // 1 pointer can remain on stack or elsewhere
116 if fin1
= atomic
.LoadUint32(&fin
); fin1
>= N
-1 {
120 t
.Fatalf("only %v out of %v resources are finalized on try %v", fin1
, N
, try
)
124 func TestPoolStress(t
*testing
.T
) {
131 done
:= make(chan bool)
132 for i
:= 0; i
< P
; i
++ {
134 var v
interface{} = 0
135 for j
:= 0; j
< N
; j
++ {
141 if v
!= nil && v
.(int) != 0 {
142 t
.Errorf("expect 0, got %v", v
)
149 for i
:= 0; i
< P
; i
++ {
154 func BenchmarkPool(b
*testing
.B
) {
156 b
.RunParallel(func(pb
*testing
.PB
) {
164 func BenchmarkPoolOverflow(b
*testing
.B
) {
166 b
.RunParallel(func(pb
*testing
.PB
) {
168 for b
:= 0; b
< 100; b
++ {
171 for b
:= 0; b
< 100; b
++ {