Created
September 7, 2012 19:49
-
-
Save jordanorelli/3669071 to your computer and use it in GitHub Desktop.
channel example
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 produce(c chan int) { | |
// loop indefinitely | |
for { | |
// write a random number from 0 to 99 into the channel | |
c <- rand.Intn(100) | |
// sleep for 0 to 9 milliseconds | |
time.Sleep(time.Millisecond * time.Duration(rand.Intn(10))) | |
} | |
} | |
func main() { | |
rand.Seed(time.Now().Unix()) | |
// create a channel for communicating ints across goroutines. | |
c := make(chan int) | |
// run the producer in a new goroutine | |
// pass it the channel so that it knows where to send values | |
go produce(c) | |
// read values off of the channel and print them (forever) | |
for i := range c { | |
fmt.Println(i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment