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.
15 func TestCondSignal(t
*testing
.T
) {
19 running
:= make(chan bool, n
)
20 awake
:= make(chan bool, n
)
21 for i
:= 0; i
< n
; i
++ {
30 for i
:= 0; i
< n
; i
++ {
31 <-running
// Wait for everyone to run.
36 t
.Fatal("goroutine not asleep")
42 <-awake
// Will deadlock if no goroutine wakes up
45 t
.Fatal("too many goroutines awake")
53 func TestCondSignalGenerations(t
*testing
.T
) {
57 running
:= make(chan bool, n
)
58 awake
:= make(chan int, n
)
59 for i
:= 0; i
< n
; i
++ {
70 t
.Fatalf("wrong goroutine woke up: want %d, got %d", i
-1, a
)
80 func TestCondBroadcast(t
*testing
.T
) {
84 running
:= make(chan int, n
)
85 awake
:= make(chan int, n
)
87 for i
:= 0; i
< n
; i
++ {
98 for i
:= 0; i
< n
; i
++ {
99 for i
:= 0; i
< n
; i
++ {
100 <-running
// Will deadlock unless n are running.
109 t
.Fatal("goroutine not asleep")
115 seen
:= make([]bool, n
)
116 for i
:= 0; i
< n
; i
++ {
119 t
.Fatal("goroutine woke up twice")
126 t
.Fatal("goroutine did not exit")
132 func TestRace(t
*testing
.T
) {
134 c
:= NewCond(&Mutex
{})
135 done
:= make(chan bool)
188 func TestCondSignalStealing(t
*testing
.T
) {
189 for iters
:= 0; iters
< 1000; iters
++ {
194 ch
:= make(chan struct{})
208 // We know that the waiter is in the cond.Wait() call because we
209 // synchronized with it, then acquired/released the mutex it was
210 // holding when we synchronized.
212 // Start two goroutines that will race: one will broadcast on
213 // the cond var, the other will wait on it.
215 // The new waiter may or may not get notified, but the first one
216 // has to be notified.
230 // Check that the first waiter does get signaled.
233 case <-time
.After(2 * time
.Second
):
234 t
.Fatalf("First waiter didn't get broadcast.")
237 // Release the second waiter in case it didn't get the
246 func TestCondCopy(t
*testing
.T
) {
249 if err
== nil || err
.(string) != "sync.Cond is copied" {
250 t
.Fatalf("got %v, expect sync.Cond is copied", err
)
253 c
:= Cond
{L
: &Mutex
{}}
256 reflect
.ValueOf(&c2
).Elem().Set(reflect
.ValueOf(&c
).Elem()) // c2 := c, hidden from vet
260 func BenchmarkCond1(b
*testing
.B
) {
264 func BenchmarkCond2(b
*testing
.B
) {
268 func BenchmarkCond4(b
*testing
.B
) {
272 func BenchmarkCond8(b
*testing
.B
) {
276 func BenchmarkCond16(b
*testing
.B
) {
280 func BenchmarkCond32(b
*testing
.B
) {
284 func benchmarkCond(b
*testing
.B
, waiters
int) {
285 c
:= NewCond(&Mutex
{})
286 done
:= make(chan bool)
289 for routine
:= 0; routine
< waiters
+1; routine
++ {
291 for i
:= 0; i
< b
.N
; i
++ {
313 for routine
:= 0; routine
< waiters
+1; routine
++ {