Created
June 4, 2019 03:51
-
-
Save santosh/6010df4949e7efc637d480ac98e83924 to your computer and use it in GitHub Desktop.
Simplest example of channels in Go. #golang
This file contains hidden or 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" | |
"math/rand" | |
"time" | |
) | |
func boring(msg string, c chan string) <-chan string { | |
for i := 0; ; i++ { | |
// putting data into the channel | |
c <- fmt.Sprintf("%-10v %d\n", msg, i) | |
// sleep for random time | |
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) | |
} | |
return c | |
} | |
func main() { | |
c := make(chan string) | |
go boring("Santosh", c) | |
go boring("Jennifer", c) | |
go boring("Himanshi", c) | |
for i := 0; i < 15; i++ { | |
// direction of arrow is the data flow | |
fmt.Printf("You say: %q\n", <-c) | |
} | |
} | |
// Checkout 'Google I/O 2012 - Go Concurrency Patterns' for more: | |
// https://www.youtube.com/watch?v=f6kdp27TYZs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment