Created
January 18, 2013 06:09
-
-
Save Veejay/4562695 to your computer and use it in GitHub Desktop.
Example of channel communication with a simple select statement. Taken from Rob Pike's slides about concurrency in Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func boring(msg string) <-chan string { // Returns receive-only channel of strings. | |
c := make(chan string) | |
go func() { // We launch the goroutine from inside the function. | |
for i := 0; ; i++ { | |
c <- fmt.Sprintf("%s %d", msg, i) | |
time.Sleep(400 * time.Millisecond) | |
} | |
}() | |
return c // Return the channel to the caller. | |
} | |
func main() { | |
c := boring("Joe") | |
timeout := time.After(2 * time.Second) | |
for { | |
select { | |
case s := <-c: | |
fmt.Println(s) | |
case <-timeout: | |
fmt.Println("You talk too much.") | |
return | |
} | |
} | |
} |
Author
Veejay
commented
Jan 18, 2013
- The channel is returned to the main before the boring function finishes
- The time.After function actually returns a channel on which the current time will be sent after the specified interval.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment