我正在尝试创建异步频道,我一直在关注http://golang.org/ref/spec#Making_slices_maps_and_channels。
c := make(chan int, 10) // channel with a buffer size of 10
缓冲区大小是10是什么意思?缓冲区大小具体表示/限制是什么?
答案 0 :(得分:139)
缓冲区大小是可以在没有发送阻止的情况下发送到通道的元素数。默认情况下,通道的缓冲区大小为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
答案 1 :(得分:5)
答案 2 :(得分:0)
package main
import (
"fmt"
"time"
)
func receiver(ch <-chan int) {
time.Sleep(500 * time.Millisecond)
msg := <-ch
fmt.Printf("receive messages %d from the channel\n", msg)
}
func main() {
start := time.Now()
zero_buffer_ch := make(chan int, 0)
go receiver(zero_buffer_ch)
zero_buffer_ch <- 444
elapsed := time.Since(start)
fmt.Printf("Elapsed using zero_buffer channel: %v\n", elapsed)
restart := time.Now()
non_zero_buffer_ch := make(chan int, 1)
go receiver(non_zero_buffer_ch)
non_zero_buffer_ch <- 4444
reelapsed := time.Since(restart)
fmt.Printf("Elapsed using non zero_buffer channel: %v\n", reelapsed)
}
结果:
从频道接收消息444
使用zero_buffer通道经过的时间:505.6729ms
使用非零缓冲区通道经过的时间:0秒