这是一个使用sync.WaitGroup来做你正在寻找的事情的例子,这个例子接受一个很长的整数列表,然后通过向 N 个并行工作人员处理一个相等大小的输入数据块来将它们全部相加。它可以在go playground上运行:package mainimport ( "fmt" "sync")const WorkerCount = 10func main() { // Some input data to operate on. // Each worker gets an equal share to work on. data := make([]int, WorkerCount*10) for i := range data { data[i] = i } // Sum all the entries. result := sum(data) fmt.Printf("Sum: %d\n", result)}// sum adds up the numbers in the given list, by having the operation delegated// to workers operating in parallel on sub-slices of the input data.func sum(data []int) int { var sum int result := make(chan int) defer close(result) // Accumulate results from workers. go func() { for { select { case value := <-result: sum += value } } }() // The WaitGroup will track completion of all our workers. wg := new(sync.WaitGroup) wg.Add(WorkerCount) // Divide the work up over the number of workers. chunkSize := len(data) / WorkerCount // Spawn workers. for i := 0; i < WorkerCount; i++ { go func(i int) { offset := i * chunkSize worker(result, data[offset:offset+chunkSize]) wg.Done() }(i) } // Wait for all workers to finish, before returning the result. wg.Wait() return sum}// worker sums up the numbers in the given list.func worker(result chan int, data []int) { var sum int for _, v := range data { sum += v } result <- sum}