func main() { numbers := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5} // Example array totalSum := concurrentSum(numbers, parts) // Divide the array into 4 parts for summing fmt.Println("Total Sum:", totalSum) }
// sumPart sums a part of the array and sends the result to a channel. func sumPart(workerId int, nums []int, result chan<- int, wg *sync.WaitGroup) { defer wg.Done() // Ensure the WaitGroup counter decrements on function completion. sum := 0 for _, num := range nums { sum += num } fmt.Printf("Worker %d calculated sum: %d\n", workerId, sum) result <- sum // Send the partial sum to the result channel. }
// concurrentSum takes an array and the number of parts to divide it into, // then sums the array elements using concurrent goroutines. func concurrentSum(numbers []int, parts int) int { n := len(numbers) partSize := n / parts // Determine the size of each subarray fmt.Printf("Dividing the array of size %d into %d parts of size %d\n", n, parts, partSize) results := make(chan int, parts) // Channel to collect results with a buffer size var wg sync.WaitGroup // Fork step: Launch a goroutine for each part of the array for i := 0; i < parts; i++ { start := i * partSize end := start + partSize if i == parts-1 { // Ensure the last goroutine covers the remainder of the array end = n } wg.Add(1) go sumPart(i, numbers[start:end], results, &wg) }
// Close the results channel once all goroutines are done go func() { wg.Wait() close(results) }()
// Join step: Combine results totalSum := 0 for sum := range results { fmt.Printf("Received partial sum: %d\n", sum) totalSum += sum }
return totalSum }
结论
上面的示例展示了使用 Go 进行并发编程时 fork/join 模式的效率。通过将数组求和的任务分给多个 Worker,程序在多核处理器上的运行速度明显加快,使用 Go 进行并发编程任务具有的强大功能和简便性。这种模式同样可应用于其他各种计算问题。
-------------The End-------------
subscribe to my blog by scanning my public wechat account