59 lines
867 B
Go
59 lines
867 B
Go
package channel
|
|
|
|
import (
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestChan(t *testing.T) {
|
|
t.Run("close", func(t *testing.T) {
|
|
ch := NewSingle()
|
|
wg := sync.WaitGroup{}
|
|
wg.Add(2)
|
|
go func() {
|
|
ch.Send()
|
|
//ch.Send()
|
|
close(ch)
|
|
tmp, ok := <-ch
|
|
t.Log("after close", tmp, ok)
|
|
wg.Done()
|
|
}()
|
|
|
|
go func() {
|
|
tmp, ok := <-ch
|
|
t.Log(tmp, ok)
|
|
wg.Done()
|
|
}()
|
|
|
|
wg.Wait()
|
|
})
|
|
}
|
|
|
|
func TestIntChan(t *testing.T) {
|
|
wg := sync.WaitGroup{}
|
|
wg.Add(2)
|
|
buf := 5
|
|
|
|
ch := NewBufferInt(buf)
|
|
go func() {
|
|
defer wg.Done()
|
|
for cnt := buf; cnt > 0; cnt-- {
|
|
ch.Send(1)
|
|
}
|
|
// 不 close ranger read 会永久阻塞
|
|
close(ch)
|
|
}()
|
|
|
|
go func() {
|
|
defer wg.Done()
|
|
<-time.After(time.Second)
|
|
t.Logf("channel len:%d cap: %d\n", len(ch), cap(ch))
|
|
for i := range ch {
|
|
_ = i
|
|
}
|
|
}()
|
|
wg.Wait()
|
|
t.Logf("channel len:%d cap: %d\n", len(ch), cap(ch))
|
|
}
|