Last active
August 29, 2015 14:04
-
-
Save ryandotsmith/0a546cca7c4767333c65 to your computer and use it in GitHub Desktop.
sync.Cond test cases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"testing" | |
"sync" | |
"sync/atomic" | |
) | |
type EasyCond struct { | |
m *sync.Mutex | |
c *sync.Cond | |
} | |
func NewEasyCond() *EasyCond { | |
m := &sync.Mutex{} | |
c := sync.NewCond(m) | |
return &EasyCond{m: m, c: c} | |
} | |
func (e *EasyCond) Wait() { | |
e.m.Lock() | |
defer e.m.Unlock() | |
e.c.Wait() | |
} | |
func (e *EasyCond) Broadcast() { | |
e.m.Lock() | |
defer e.m.Unlock() | |
e.c.Broadcast() | |
} | |
func TestCond(t *testing.T) { | |
expected := int32(2) | |
actual := int32(0) | |
running := make(chan bool, expected) | |
finished := make(chan bool, expected) | |
var mutex sync.Mutex | |
cond := sync.NewCond(&mutex) | |
for i := int32(0); i < expected; i++ { | |
go func() { | |
running <- true | |
mutex.Lock() | |
cond.Wait() | |
mutex.Unlock() | |
atomic.AddInt32(&actual, 1) | |
finished <- true | |
}() | |
} | |
for i := int32(0); i < expected; i++ { | |
<-running | |
} | |
mutex.Lock() | |
cond.Broadcast() | |
mutex.Unlock() | |
for i := int32(0); i < expected; i++ { | |
<-finished | |
} | |
if actual != expected { | |
t.Errorf("actual=%d expected=%d\n", actual, expected) | |
} | |
} | |
func TestEasyCond(t *testing.T) { | |
expected := int32(2) | |
actual := int32(0) | |
running := make(chan bool, expected) | |
finished := make(chan bool, expected) | |
cond := NewEasyCond() | |
for i := int32(0); i < expected; i++ { | |
go func() { | |
running <- true | |
cond.Wait() | |
atomic.AddInt32(&actual, 1) | |
finished <- true | |
}() | |
} | |
for i := int32(0); i < expected; i++ { | |
<-running | |
} | |
cond.Broadcast() | |
for i := int32(0); i < expected; i++ { | |
<-finished | |
} | |
if actual != expected { | |
t.Errorf("actual=%d expected=%d\n", actual, expected) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment