channel之阻塞七
2020-03-17 本文已影响0人
anthonydan
思考:看结果结果?会不定时出现两个结果
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
var ch chan int // 未初始化,值为 nil
ch = make(chan int)
for i := 0; i < 3; i++ {
wg.Add(1)
go func(i int, group *sync.WaitGroup) {
defer group.Done()
ch <- i
}(i, &wg)
}
go func() {
fmt.Println("start select")
for {
select {
case v,ok := <-ch:
if !ok {
fmt.Println("select return")
return
}
fmt.Println(v, "select ing")
}
}
fmt.Println("select end")
}()
time.Sleep(1*time.Second)
ch <- 4
wg.Wait()
close(ch)
fmt.Println("all finish")
//var ch chan int // 未初始化,值为 nil
//ch = make(chan int)
//for i := 0; i < 3; i++ {
// go func(i int) {
// ch <- i
// }(i)
//}
//for v := range ch {
// fmt.Println(v)
//}
//close(ch)
//time.Sleep(2 * time.Second)
}
结果1:
D:\work\go\src\wm\test>go run channel6.go
start select
0 select ing
1 select ing
2 select ing
all finish
结果2:
D:\work\go\src\wm\test>go run channel6.go
start select
1 select ing
0 select ing
2 select ing
4 select ing
select return
all finish
原因:
是因为主main已经执行结束,goroutine还没执行完。