Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created September 7, 2012 19:49
Show Gist options
  • Save jordanorelli/3669071 to your computer and use it in GitHub Desktop.
Save jordanorelli/3669071 to your computer and use it in GitHub Desktop.
channel example
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