From a5156639ae66ba3857c4f31e57282b4af372526c Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Thu, 11 Oct 2012 08:10:43 -0700 Subject: [PATCH] publish channels --- examples.txt | 2 +- examples/channels/channels.go | 18 +++++++++++++++++- examples/channels/channels.sh | 10 ++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 examples/channels/channels.sh diff --git a/examples.txt b/examples.txt index bb9f78f..bb041a6 100644 --- a/examples.txt +++ b/examples.txt @@ -27,7 +27,7 @@ Maps # OK Guards Goroutines # Concurrent Goroutines -# Channels +Channels # Channel Buffering # Channel Directions # Synchronization diff --git a/examples/channels/channels.go b/examples/channels/channels.go index 589999f..af8a9bd 100644 --- a/examples/channels/channels.go +++ b/examples/channels/channels.go @@ -1,10 +1,26 @@ +// _Channels_ are the pipes that connect goroutines in a +// concurrent Go program. You can send values into +// channels from one goroutine and receive those values +// into another goroutine. + package main import "fmt" func main() { - var messages chan string = make(chan string) + + // Create a new channel with `make(chan val-type)`. + // Channels are typed by the values they convey. + messages := make(chan string) + + // _Send_ a value into a channel using the `channel <-` + // syntax. Here we send `"ping"` to the `messages` + // channel we made above, from a new goroutine. go func() { messages <- "ping" }() + + // The `<-channel` syntax _receives_ a value from the + // channel. Here we'll receive the `"ping"` message + // we sent above and print it out. msg := <-messages fmt.Println(msg) } diff --git a/examples/channels/channels.sh b/examples/channels/channels.sh new file mode 100644 index 0000000..cc394a7 --- /dev/null +++ b/examples/channels/channels.sh @@ -0,0 +1,10 @@ +# When we run the program the `"ping"` message is +# succesfully passed from one goroutine to another via our +# channel. +$ go run channels.go +ping + +# By default sends and receives block until both the +# sender and receiver are ready. This property allowed +# us to wait at the end of our program for the `"ping"` +# message without having to use any other synchronization.