面试题答案
一键面试实现思路
- 使用
sync.WaitGroup
来等待所有 Goroutine 完成任务。 - 将任务切片进行分割,分配给不同的 Goroutine。
- 利用
chan
来传递任务结果。
核心代码示例
package main
import (
"fmt"
"sync"
)
func worker(id int, tasks <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for task := range tasks {
// 模拟任务处理
result := task * 2
results <- result
}
}
func main() {
tasks := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
numWorkers := 3
taskChan := make(chan int)
resultChan := make(chan int)
var wg sync.WaitGroup
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go worker(i, taskChan, resultChan, &wg)
}
go func() {
for _, task := range tasks {
taskChan <- task
}
close(taskChan)
}()
go func() {
wg.Wait()
close(resultChan)
}()
for result := range resultChan {
fmt.Println("Result:", result)
}
}
在上述代码中:
worker
函数是每个 Goroutine 执行的任务逻辑,从tasks
通道中接收任务,处理后将结果发送到results
通道。- 在
main
函数中,创建了任务切片tasks
,并根据numWorkers
创建了相应数量的 Goroutine 来处理任务。 - 使用
sync.WaitGroup
等待所有 Goroutine 完成任务,最后从resultChan
通道中接收并打印任务结果。