parallel: 一个简单的并行运行Go循环的库


使用最新泛型,例如:对每个元素调用一次指定的函数,请注意,执行顺序是随机的:

input := []int{1, 2, 3, 4, 5, 6}

parallel.ForEach(input, func(x int) {
  fmt.Printf("Processing %d\n", x)
})

// Output:

// Processing 6
// Processing 3
// Processing 4
// Processing 5
// Processing 1
// Processing 2

使用Map:对每个元素调用一次给定的函数,并返回一个带有其结果的新片断。请注意,输出片断的元素顺序与输入片断相同,并且被保留下来,但执行顺序是随机的。

input := []int{1, 2, 3, 4, 5, 6}

result := parallel.Map(input, func(x int) int {
  fmt.Printf("Processing %d\n", x)
  return x * 2
})

fmt.Printf(
"The final result is %v\n", result)

// Output:

// Processing 6
// Processing 1
// Processing 2
// Processing 3
// Processing 4
// Processing 5
// The final result is [2 4 6 8 10 12]