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
> */
文章标题:channel的关闭和广播机制测试
分享地址:
http://cdweb.net/article/iisphd.html