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() { time.Sleep(time.Second) tmp, ok := <-ch t.Log(tmp, ok) wg.Done() }() wg.Wait() }) } func TestChClose(t *testing.T) { const ( buffer = 10 ) t.Run("send-finish-read-after", func(t *testing.T) { t.Run("for", func(t *testing.T) { ch := NewBufferSingle(buffer) wg := new(sync.WaitGroup) wg.Add(2) go func() { for i := 0; i < buffer; i++ { ch.Send() } close(ch) wg.Done() t.Log("send fin, close. ") }() go func() { time.Sleep(time.Second) for i := 0; i < buffer+1; i++ { s, ok := <-ch t.Log(s, ok) } wg.Done() }() wg.Wait() }) t.Run("for-range", func(t *testing.T) { ch := NewBufferSingle(buffer) wg := new(sync.WaitGroup) wg.Add(2) go func() { for i := 0; i < buffer; i++ { ch.Send() } close(ch) t.Log("send fin, close. ") wg.Done() }() go func() { time.Sleep(time.Second) for s := range ch { t.Log(s) } 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)) }