Last active
September 26, 2018 02:55
-
-
Save esimov/11400495 to your computer and use it in GitHub Desktop.
Filter prime numbers in Go lang concurently using goroutines
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" | |
// Generate the input values passing through the go channel pipe | |
func generate(ch chan int) { | |
go func() { | |
for i := 2; ; i++ { | |
ch <- i | |
} | |
}() | |
} | |
// Copy the value from input channel to output channel | |
func filter(in chan int, out chan int, filter int) { | |
for val := range in { | |
if val%filter != 0 { | |
out <- val // send value to the output pipe | |
} | |
} | |
} | |
func main() { | |
ch := make(chan int) // create a new a channel | |
generate(ch) | |
for { | |
prime := <- ch | |
fmt.Print(prime, " ") | |
ch1 := make(chan int) | |
go filter(ch, ch1, prime) | |
ch = ch1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment