Skip to content

Instantly share code, notes, and snippets.

@ymg
Created May 17, 2013 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ymg/d478b2d3ea9177ae50a2 to your computer and use it in GitHub Desktop.
Save ymg/d478b2d3ea9177ae50a2 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
/* initialization and assignment of channels */
c := make(chan []string)
p := make(chan []string)
/* testing multiple channels */
//p2 := make(chan []string)
/* Pass created channels to Goroutines */
go Feeder1(p)
go Feeder2(p) //switch to P2 to test multiple channels
go Consumer(c)
for {
select {
case produced := <-p:
c <- produced
//case of P2 to test multiple channels
/*case produced2 := <-p2:
c <- produced2*/
//time out case to stop the loop when communication is too slow
/*case <-time.After(6 * time.Second):
return*/
default:
fmt.Printf("\n --- We timed out! --- \n")
time.Sleep(1 * time.Second)
}
}
}
func Feeder2(w chan []string) {
headlines := []string{
"BBC: Speedboat victim 'doted on family'\n",
"BBC: Syria rebel sarin claim downplayed\n",
"BBC: German 'ex-Auschwitz guard' arrested\n",
"BBC: Armless artist 'denied entry' to UK\n",
"BBC: Bangladesh protest clashes kill 27\n",
"BBC: Ex-Italian PM Giulio Andreotti dies\n"}
for i := 0; ; i++ {
selection := []string{}
for s := 0; s <= 2; s++ {
selection = append(selection, headlines[randInt(0, len(headlines))])
}
w <- selection
time.Sleep(2 * time.Second)
}
}
func Feeder1(w chan []string) {
headlines := []string{
"SKY: Deadly Virus Can 'Spread Between People'\n",
"SKY: Ariel Castro's Brothers Brand Him 'A Monster'\n",
"SKY: Astronaut Ends Space Mission With Bowie Song\n",
"SKY: Chinese Artist Films Violent Street Brawl\n",
"SKY: May Washout: Fortnight's Rainfall In One Day\n",
"SKY: Mother's Day Shooting: CCTV Shows Suspect\n"}
for i := 0; ; i++ {
selection := []string{}
for q := 0; q <= 2; q++ {
selection = append(selection, headlines[randInt(0, len(headlines))])
}
w <- selection
//randomTimeValue := randInt(5, 6)
time.Sleep(2 * time.Second)
}
}
func Consumer(n chan []string) {
for {
v := <-n
for _, x := range v {
fmt.Printf("Headline:\t%s", x)
}
}
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment