Skip to content

Instantly share code, notes, and snippets.

@ryandotsmith
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryandotsmith/0a546cca7c4767333c65 to your computer and use it in GitHub Desktop.
Save ryandotsmith/0a546cca7c4767333c65 to your computer and use it in GitHub Desktop.
sync.Cond test cases
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