golang chanel疑惑
2018-05-11 本文已影响0人
frank3
今天看golang chan发现了一个奇怪的问题,就是1.同样的不带缓存chanel,已有数据关闭和没有数据关闭,不一样? 2. 带缓存和不带缓存的chan,已有数据关闭,也不一样?
// Copyright. All rights reserved.
package main
import (
"fmt"
"time"
"flag"
)
func main() {
c := flag.Int("c", 0, "choose")
flag.Parse()
var ch chan int
if *c == 0 || *c == 2 {
ch = make(chan int)
}else if *c == 1 {
ch = make(chan int, 1)
}
go func() {
select {
case v, ok := <- ch:
fmt.Println("1 close ", v, ok)
return
default:
fmt.Println("1 defaul")
}
}()
go func() {
select {
case v, ok := <- ch:
fmt.Println("3 close ", v, ok)
return
default:
fmt.Println("2 defaul")
}
}()
go func() {
select {
case v, ok := <- ch:
fmt.Println("3 close ", v, ok)
return
default:
fmt.Println("3 defaul")
}
}()
go func() {
select {
case v, ok := <- ch:
fmt.Println("4 close ", v, ok)
return
default:
fmt.Println("4 defaul")
}
}()
if *c != 2 {
ch <- 3
}
close(ch)
time.Sleep(time.Second)
}
输出结果:
➜ golearn git:(master) ✗ ./chan -c 1
4 close 0 false
3 close 3 true
1 close 0 false
3 close 0 false
➜ golearn git:(master) ✗ ./chan -c 0
4 close 3 true
2 defaul
1 defaul
3 defaul
➜ golearn git:(master) ✗ ./chan -c 2
4 close 0 false
1 close 0 false
3 close 0 false
3 close 0 false
问题原因还在寻找中................ 欢迎高手指点