通道缓冲区大小是多少?

我正在尝试创建一个异步通道,并且一直在查看http://golang.org/ref/spec#Making_slices_maps_and_channels

c := make(chan int, 10)         // channel with a buffer size of 10

缓冲区大小为10是什么意思?缓冲区大小具体代表/限制了什么?


呼如林
浏览 327回答 3
3回答

猛跑小猪

缓冲区大小是在没有发送阻塞的情况下可以发送到通道的元素数。默认情况下,通道的缓冲区大小为0(可通过来获得此值make(chan int))。这意味着每个发送都将阻塞,直到另一个goroutine从通道接收到为止。缓冲区大小为1的通道可以容纳1个元素,直到发送块为止,因此您将获得c := make(chan int, 1)c <- 1 // doesn't blockc <- 2 // blocks until another goroutine receives from the channel

摇曳的蔷薇

以下代码说明了对非缓冲通道的阻塞:// to see the diff, change 0 to 1c := make(chan struct{}, 0)go func() {&nbsp; &nbsp; time.Sleep(2 * time.Second)&nbsp; &nbsp; <-c}()start := time.Now()c <- struct{}{} // block, if channel size is 0elapsed := time.Since(start)fmt.Printf("Elapsed: %v\n", elapsed)您可以在此处使用代码。

FFIVE

package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time")func receiver(ch <-chan int) {&nbsp; &nbsp; time.Sleep(500 * time.Millisecond)&nbsp; &nbsp; msg := <-ch&nbsp; &nbsp; fmt.Printf("receive messages&nbsp; %d from the channel\n", msg)}func main() {&nbsp; &nbsp; start := time.Now()&nbsp; &nbsp; zero_buffer_ch := make(chan int, 0)&nbsp; &nbsp; go receiver(zero_buffer_ch)&nbsp; &nbsp; zero_buffer_ch <- 444&nbsp; &nbsp; elapsed := time.Since(start)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; fmt.Printf("Elapsed using zero_buffer channel: %v\n", elapsed)&nbsp; &nbsp; restart := time.Now()&nbsp; &nbsp; non_zero_buffer_ch := make(chan int, 1)&nbsp; &nbsp; go receiver(non_zero_buffer_ch)&nbsp; &nbsp; non_zero_buffer_ch <- 4444&nbsp; &nbsp; reelapsed := time.Since(restart)&nbsp; &nbsp; fmt.Printf("Elapsed using non zero_buffer channel: %v\n", reelapsed)}结果:从通道接收消息444使用zero_buffer通道经过的时间:505.6729ms使用非zero_buffer通道经过的时间:0s
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go