我正在尝试创建一个异步通道,我一直在关注http://golang.org/ref/spec#Making_slices_maps_and_channels.
c := make(chan int, 10) // channel with a buffer size of 10
Run Code Online (Sandbox Code Playgroud)
缓冲区大小是10是什么意思?具体的缓冲区大小是什么代表/限制?
Lil*_*ard 147
缓冲区大小是可以在没有发送阻止的情况下发送到通道的元素数.默认情况下,通道的缓冲区大小为0(您可以使用此方法make(chan int)).这意味着每个发送都会阻塞,直到另一个goroutine从该频道收到.缓冲区大小为1的通道可以容纳1个元素直到发送块,所以你得到
c := make(chan int, 1)
c <- 1 // doesn't block
c <- 2 // blocks until another goroutine receives from the channel
Run Code Online (Sandbox Code Playgroud)
以下代码说明了对非缓冲通道的阻塞:
// to see the diff, change 0 to 1
c := make(chan struct{}, 0)
go func() {
time.Sleep(2 * time.Second)
<-c
}()
start := time.Now()
c <- struct{}{} // block, if channel size is 0
elapsed := time.Since(start)
fmt.Printf("Elapsed: %v\n", elapsed)
Run Code Online (Sandbox Code Playgroud)
您可以在此处使用代码。