Created
September 30, 2015 15:54
-
-
Save mukulrawat1986/7d2a0eb172a3cc872268 to your computer and use it in GitHub Desktop.
This file contains 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
// 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