1 // Copyright 2011 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.
14 func testWaitGroup(t
*testing
.T
, wg1
*WaitGroup
, wg2
*WaitGroup
) {
18 exited
:= make(chan bool, n
)
19 for i
:= 0; i
!= n
; i
++ {
27 for i
:= 0; i
!= n
; i
++ {
30 t
.Fatal("WaitGroup released group too soon")
35 for i
:= 0; i
!= n
; i
++ {
36 <-exited
// Will block if barrier fails to unlock someone.
40 func TestWaitGroup(t
*testing
.T
) {
44 // Run the same test a few times to ensure barrier is in a proper state.
45 for i
:= 0; i
!= 8; i
++ {
46 testWaitGroup(t
, wg1
, wg2
)
50 func TestWaitGroupMisuse(t
*testing
.T
) {
53 if err
!= "sync: negative WaitGroup counter" {
54 t
.Fatalf("Unexpected panic: %#v", err
)
61 t
.Fatal("Should panic")
64 func BenchmarkWaitGroupUncontended(b
*testing
.B
) {
65 type PaddedWaitGroup
struct {
69 const CallsPerSched
= 1000
70 procs
:= runtime
.GOMAXPROCS(-1)
71 N
:= int32(b
.N
/ CallsPerSched
)
72 c
:= make(chan bool, procs
)
73 for p
:= 0; p
< procs
; p
++ {
75 var wg PaddedWaitGroup
76 for atomic
.AddInt32(&N
, -1) >= 0 {
78 for g
:= 0; g
< CallsPerSched
; g
++ {
87 for p
:= 0; p
< procs
; p
++ {
92 func benchmarkWaitGroupAddDone(b
*testing
.B
, localWork
int) {
93 const CallsPerSched
= 1000
94 procs
:= runtime
.GOMAXPROCS(-1)
95 N
:= int32(b
.N
/ CallsPerSched
)
96 c
:= make(chan bool, procs
)
98 for p
:= 0; p
< procs
; p
++ {
101 for atomic
.AddInt32(&N
, -1) >= 0 {
103 for g
:= 0; g
< CallsPerSched
; g
++ {
105 for i
:= 0; i
< localWork
; i
++ {
115 for p
:= 0; p
< procs
; p
++ {
120 func BenchmarkWaitGroupAddDone(b
*testing
.B
) {
121 benchmarkWaitGroupAddDone(b
, 0)
124 func BenchmarkWaitGroupAddDoneWork(b
*testing
.B
) {
125 benchmarkWaitGroupAddDone(b
, 100)
128 func benchmarkWaitGroupWait(b
*testing
.B
, localWork
int) {
129 const CallsPerSched
= 1000
130 procs
:= runtime
.GOMAXPROCS(-1)
131 N
:= int32(b
.N
/ CallsPerSched
)
132 c
:= make(chan bool, procs
)
135 for p
:= 0; p
< procs
; p
++ {
138 for p
:= 0; p
< procs
; p
++ {
141 for atomic
.AddInt32(&N
, -1) >= 0 {
143 for g
:= 0; g
< CallsPerSched
; g
++ {
145 for i
:= 0; i
< localWork
; i
++ {
154 for p
:= 0; p
< procs
; p
++ {
159 func BenchmarkWaitGroupWait(b
*testing
.B
) {
160 benchmarkWaitGroupWait(b
, 0)
163 func BenchmarkWaitGroupWaitWork(b
*testing
.B
) {
164 benchmarkWaitGroupWait(b
, 100)