golang中Channel通道(二)
一、带缓冲和不带缓冲的通道的区别
1、非缓冲通道
一次发送操作对应一次接收操作,对于一个goroutine来讲,它的一次发送,在另一个goroutine接收之前都是阻塞的。同样的,对于接收来讲,在另一个goroutine发送之前,它也是阻塞的。
2、缓冲通道
缓冲通道就是指一个通道,带有一个缓冲区。发送到一个缓冲通道只有在缓冲区满时才被阻塞。类似地,从缓冲通道接收的信息只有在缓冲区为空时才会被阻塞。
可以通过将额外的容量参数传递给make函数来创建缓冲通道,该函数指定缓冲区的大小。语法:
ch := make(chan type,capacity)
上述语法的容量应该大于0,以便通道具有缓冲区。默认情况下,无缓冲通道的容量为0,因此在之前创建通道时省略了容量参数。
实例:
package main
import "fmt"
//带缓冲和不带缓冲的通道
func main() {
ch1:=make(chan int) //非缓冲区通道
fmt.Println(len(ch1),cap(ch1)) //0 0
//ch1 <- 100 //阻塞式的,需要有其他的goroutine解除阻塞,否则deadlock
ch2:=make(chan int, 5) //缓冲区通道
fmt.Println(len(ch2),cap(ch2)) //0 5
ch2 <- 100
fmt.Println(len(ch2),cap(ch2)) //1 5
ch2 <- 200
ch2 <- 300
ch2 <- 400
ch2 <- 500
fmt.Println(len(ch2),cap(ch2)) //5 5
//ch2 <- 600 //deadlock
}
二、单向通道和双向通道
1、双向通道
通道,channel,是用于实现goroutine之间的通信的。一个goroutine可以向通道中发送数据,另一条goroutine可以从该通道中获取数据。既可以发送数据,也可以读取数据,我们又把这种通道叫做双向通道。
data := <- a / / read from channel a
a <- data / / write to channel a
2、单向通道
单向通道,也就是定向通道。可以通过这些通道接收或者发送数据。我们也可以创建单向通道,这些通道只能发送或者接收数据。
实例:
package main
import "fmt"
//单向通道
func main() {
ch1 :=make(chan int)//双向,读,写
//ch2 :=make(chan<- int)//单向,只能写,不能读
//ch3 := make(<- chan int)//单向,只能读,不能写
//ch1 <-100
//data:=<-ch1
//ch2 <-1000
//data := <- ch2 //invalid operation: <-ch2 (receive from send-only type chan<- int)
//data :=<- ch3
//ch3 <- 2000 //invalid operation: ch3 <- 2000(send to receive-only type <-chan int)
go fun1(ch1)//可读,可写
//go fun1(ch2)//只写
data :=<-ch1
fmt.Println( "fun1函数中写出的数据是:",data)
}
func fun1(ch chan <- int) {
ch <- 100
fmt.Println("fun1函数结束。。。")
}