示例demo52
package main
import (
”fmt”
)
func calc(taskChan chan int, resChan chan int, exitChan chan bool) {
for v := range taskChan {
flag := true
for i := 2; i < v; i++ {
if v%i == 0 {
flag = false
break
}
}
if flag {
//值放到resChan 通道里
resChan <- v
}
}
fmt.Println(“exit”)
exitChan <- true
}
func main() {
intChan := make(chan int, 1000) //初始化 intchan 通道 长度1000
resultChan := make(chan int, 1000) //初始化 resultChan通道 长度1000
closeChan := make(chan bool, 8)
go func() { //协程方式放进10000个数到intChan通道里
for i := 0; i < 100000; i++ {
intChan <- i
}
close(intChan) //关闭intChan通道
}()
//启8个协程 运行计算 传入intChan 和resultChan
for i := 0; i < 8; i++ {
go calc(intChan, resultChan, closeChan)
}
//等待所有计算的goroutine全部退出
go func() {
for i := 0; i < 8; i++ {
<-closeChan
}
close(closeChan) //关闭closeChan通道
close(resultChan) //关闭resultChan通道
}()
//循环 resultChan遍历数据
for v := range resultChan {
fmt.Println(v)
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/281491.html