func Filter(in <-chan int, out chan<- int, prime int) {
for {
i := <-in
if i%prime != 0 {
out <- i
}
}
}
func Generate(ch chan<- int) {
for i := 2; ; i++ {
ch <- i
}
}
func main() {
ch := make(chan int)
go Generate(ch)
// print the first 10 prime numbers
for i := 0; i < 10; i++ {
prime := <-ch
println("next prime = ", prime)
ch1 := make(chan int)
go Filter(ch, ch1, prime)
ch = ch1
}
}
func Filter(in <-chan int, out chan<- int, prime int) {
for {
i := <-in
if i%prime != 0 {
out <- i
}
}
}
func main() {
ch := make(chan int)
go func() {
for i := 2; ; i++ {
ch <- i
}
}()
for i := 0; i < 10; i++ {
prime := <-ch
println("next prime = ", prime)
ch1 := make(chan int)
go Filter(ch, ch1, prime)
ch = ch1
}
}
运行后发现上面的代码可以实现并发素数筛的功能, 但是下面的闭包写法就不行, 有没有大佬解释一下?
|