设计思路
- 任务分发:使用一个带缓冲的通道来存放任务。可以将1000个数字依次发送到这个通道中,供工作协程获取任务。
- 工作协程:启动多个工作协程,每个工作协程从任务通道中获取任务,执行平方运算,并将结果发送到结果通道。
- 结果收集:使用另一个带缓冲的通道来收集工作协程返回的结果。主协程从这个结果通道中获取并处理最终结果。
核心代码示例
package main
import (
"fmt"
)
func worker(taskChan <-chan int, resultChan chan<- int) {
for num := range taskChan {
result := num * num
resultChan <- result
}
close(resultChan)
}
func main() {
const taskCount = 1000
taskChan := make(chan int, taskCount)
resultChan := make(chan int, taskCount)
// 启动工作协程
const workerCount = 10
for i := 0; i < workerCount; i++ {
go worker(taskChan, resultChan)
}
// 分发任务
for i := 1; i <= taskCount; i++ {
taskChan <- i
}
close(taskChan)
// 收集结果
var results []int
for result := range resultChan {
results = append(results, result)
}
// 处理结果
for _, res := range results {
fmt.Println(res)
}
}