重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
package csp import ( "fmt" "sync" "testing" ) /* func dataProducer(ch chan int, wg *sync.WaitGroup) { go func() { for i := 0; i < 10; i++ { ch <- i } wg.Done() }() } func dataReceiver(ch chan int, wg *sync.WaitGroup) { go func() { for i := 0; i < 10; i++ { data := <-ch fmt.Println(data) } wg.Done() }() } func TestChannelClose(t *testing.T) { ch := make(chan int) var wg sync.WaitGroup wg.Add(1) dataProducer(ch, &wg) wg.Add(1) dataReceiver(ch, &wg) wg.Wait() } */ func dataProducer(ch chan int, wg *sync.WaitGroup) { go func() { for i := 0; i < 10; i++ { ch <- i } close(ch) //没有加closepanic了 wg.Done() }() } func dataReceiver(ch chan int, wg *sync.WaitGroup) { go func() { for { if data, ok := <-ch; ok { fmt.Println(data) } else { break } } wg.Done() }() } func TestChannelClose(t *testing.T) { ch := make(chan int) var wg sync.WaitGroup wg.Add(1) dataProducer(ch, &wg) wg.Add(1) dataReceiver(ch, &wg) // wg.Add(1) // dataReceiver(ch, &wg) // wg.Add(1) // dataReceiver(ch, &wg) wg.Wait() } /*>go test 0 1 2 3 4 5 6 7 8 9 PASS ok 0.249s > */ /* func TestChannelClose(t *testing.T) { ch := make(chan int) var wg sync.WaitGroup wg.Add(1) dataProducer(ch, &wg) wg.Add(1) dataReceiver(ch, &wg) wg.Add(1) dataReceiver(ch, &wg) wg.Add(1) dataReceiver(ch, &wg) wg.Wait() } >go test 0 1 4 5 6 7 8 9 3 2 PASS ok 0.360s > */