Skip to content

Instantly share code, notes, and snippets.

@mukulrawat1986
Created September 30, 2015 15:54
Show Gist options
  • Save mukulrawat1986/7d2a0eb172a3cc872268 to your computer and use it in GitHub Desktop.
Save mukulrawat1986/7d2a0eb172a3cc872268 to your computer and use it in GitHub Desktop.
// A concurrent CracklePop Program
package main
import (
"fmt"
)
// Create a goroutine that sends infinite empty string on a channel
// and returns the channel
func generate() chan string {
c := make(chan string)
go func() {
for {
c <- ""
}
}()
return c
}
// Creates a goroutine that takes a channel and modifies it so that
// it returns a string s on the new after every x incoming messages on the channel.
// The function returns a new channel
func filter(c chan string, x int, s string) chan string {
ch := make(chan string)
go func() {
count := 0
for {
i := <-c
count += 1
if count%x == 0 {
ch <- i + s
count = 0
} else {
ch <- i
}
}
}()
return ch
}
func main() {
// create a goroutine that sends infinite empty strings on c
c := generate()
// create a goroutine that modifies channel c to add Crackle
// to the string after every 3 string
c1 := filter(c, 3, "Crackle")
// create a goroutine that modifies channel c1 to add Pop to the
// string after every 5 strings
c2 := filter(c1, 5, "Pop")
for i := 1; i <= 100; i++ {
if s := <-c2; s != "" {
fmt.Printf("%s\n", s)
} else {
fmt.Printf("%d\n", i)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment