1.golang并行示例(1)
package main
import (
"fmt"
)
func Processor(seq chan int,wait chan struct{}){ //迭代方式实现并行go func()
go func() {
prime, ok := <-seq
if !ok {
close(wait)
return
}
fmt.Println(prime)
out := make(chan int)
Processor(out, wait)
for num := range seq { //for循环取chan值避免chan阻塞
if num%prime != 0 {
out <- num
}
}
close(out)
}()
}
func main() {
origin,wait := make(chan int),make(chan struct{})
Processor(origin,wait) //processor放在for循环前防止deadlock
for num:=2;num<10000;num++ {
origin <-num
}
close(origin)
<-wait
}
有疑问加站长微信联系(非本文作者)