Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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