publish channel-buffering

This commit is contained in:
Mark McGranaghan 2012-10-18 06:07:19 -07:00
parent f79d9e151f
commit 86867c9cff
3 changed files with 25 additions and 5 deletions

View File

@ -26,7 +26,7 @@ Recursion
# OK Guards # OK Guards
Goroutines Goroutines
Channels Channels
# Channel Buffering Channel Buffering
# Channel Directions # Channel Directions
# Synchronization # Synchronization
Select Select

View File

@ -1,10 +1,27 @@
// By default channels are _unbuffered_, meaning that they
// will only accept sends (`chan <-`) if there is a
// corresponding receive (`<- chan`) ready to receive the
// sent value. _Buffered channels_ accept a limited
// number of values without a corresponding receiver for
// those values.
package main package main
import "fmt" import "fmt"
func main() { func main() {
var messages chan string = make(chan string, 1)
messages <- "ping" // Here we `make` a channel of strings buffering up to
msg := <-messages // 2 values.
fmt.Println(msg) 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)
} }

View File

@ -0,0 +1,3 @@
$ go run channel-buffering.go
buffered
channel