funccloseChan(primeChan chanint) { for { if count == 0 { close(primeChan) break } } }
funcprimeNum(intChan chanint, primeChan chanint) { for num := range intChan { if isPrime(num) == true { primeChan <- num } } // 能执行到这一步说明intChan中已经没有数据了。 count-- }
funcisPrime(p int)bool { if p == 1 { returnfalse } for i := 2; i < int(math.Sqrt(float64(p))); i++ { if p%2 == 0 { returnfalse } } returntrue }
var wg sync.WaitGroup var count int = 16 var mutex sync.Mutex
funcputNum(intChan chanint) { for i := 2; i < 100000; i++ { intChan <- i } close(intChan) wg.Done() }
funcprimeNum(intChan chanint, primeChan chanint) { for num := range intChan { if isPrime(num) == true { primeChan <- num } } mutex.Lock() count-- mutex.Unlock() wg.Done() }
funcprintPrime(primeChan chanint) { for _ = range primeChan { //这里使用_是因为数据太多就不打印了。 // fmt.Printf("v: %v\n", v) } wg.Done() }
funccloseChan(primeChan chanint) { for { if count == 0 { close(primeChan) break } } wg.Done() }
funcmain() { start := time.Now().UnixMilli() intChan := make(chanint, 10000) primeChan := make(chanint, 10000) wg.Add(1) go putNum(intChan) for i := 0; i < 16; i++ { wg.Add(1) go primeNum(intChan, primeChan) } wg.Add(1) go closeChan(primeChan) wg.Add(1) go printPrime(primeChan) wg.Wait() end := time.Now().UnixMilli()