go版本
go version go1.11.2 linux/amd64
无缓冲通道
测试样例
package main
import "fmt"
func main(){
naturals:=make(chan int,0)//无缓存通道
squares:=make(chan int)
go func(){
for x:=0;x<10;x++{
fmt.Println("naturals start ",x)
naturals<-x
fmt.Println("naturals end ",x)
}
fmt.Println("naturals close ")
close(naturals)
}()
go func(){
for x:=range naturals{
fmt.Println("squares start ",x)
squares<-x
fmt.Println("squares end ",x)
}
fmt.Println("squares close ")
close(squares)
}()
for x:=range squares{
fmt.Println("main ",x)
}
}
输出
naturals start 0
naturals end 0
naturals start 1
squares start 0
squares end 0
squares start 1
naturals end 1
naturals start 2
main 0
main 1
squares end 1
squares start 2
squares end 2
main 2
naturals end 2
naturals start 3
naturals end 3
naturals start 4
squares start 3
squares end 3
squares start 4
naturals end 4
naturals start 5
main 3
main 4
squares end 4
squares start 5
squares end 5
main 5
naturals end 5
naturals start 6
naturals end 6
naturals start 7
squares start 6
squares end 6
squares start 7
naturals end 7
naturals start 8
main 6
main 7
squares end 7
squares start 8
squares end 8
main 8
naturals end 8
naturals start 9
naturals end 9
naturals close
squares start 9
squares end 9
squares close
main 9
总结
重点是开头的
naturals start 0
naturals end 0
naturals start 1
squares start 0
无缓冲通道可以塞进一个信息,然后继续往下走,
如果这个信息还没有接收,继续发送消息,则会造成阻塞,会切换到另外一个goroutine
有缓冲通道
测试样例
package main
import "fmt"
func main(){
naturals:=make(chan int,1)//有缓存通道 容量为1
squares:=make(chan int)
go func(){
for x:=0;x<10;x++{
fmt.Println("naturals start ",x)
naturals<-x
fmt.Println("naturals end ",x)
}
fmt.Println("naturals close ")
close(naturals)
}()
go func(){
for x:=range naturals{
fmt.Println("squares start ",x)
squares<-x
fmt.Println("squares end ",x)
}
fmt.Println("squares close ")
close(squares)
}()
for x:=range squares{
fmt.Println("main ",x)
}
}
输出
naturals start 0
naturals end 0
naturals start 1
naturals end 1
naturals start 2
squares start 0
squares end 0
squares start 1
naturals end 2
naturals start 3
main 0
main 1
squares end 1
squares start 2
squares end 2
squares start 3
main 2
main 3
squares end 3
naturals end 3
naturals start 4
naturals end 4
naturals start 5
naturals end 5
naturals start 6
squares start 4
squares end 4
squares start 5
naturals end 6
naturals start 7
main 4
main 5
squares end 5
squares start 6
squares end 6
squares start 7
main 6
main 7
squares end 7
naturals end 7
naturals start 8
naturals end 8
naturals start 9
naturals end 9
naturals close
squares start 8
squares end 8
squares start 9
main 8
main 9
squares end 9
squares close
总结
重点是开头的
naturals start 0
naturals end 0
naturals start 1
naturals end 1
naturals start 2
squares start 0
容量为1的有缓冲通道可以塞进2个信息,然后继续往下走,
如果这2个信息还没有接收,继续发送消息,则会造成阻塞,会切换到另外一个goroutine
有疑问加站长微信联系(非本文作者)