在Go语言中是否有像OpenMP那样简单的`parallel for`功能?

huangapple go评论135阅读模式
英文:

Is there a simple `parallel for` in golang like OpenMP?

问题

我正在尝试使用并行处理来优化一个谜题,以提高性能。

理想情况下,在C99中使用OpenMP,我应该能够在相关的for循环之前使用#pragma omp parallel for来实现并行处理,然后系统会自动在CPU之间分配负载。

然而,Go的官方文档(https://golang.org/doc/effective_go.html#parallel)似乎暗示了为了进行并行处理,我必须:(0)手动从运行时环境获取核心数,(1)循环遍历这些核心,(2)为每个核心编写一个独立的for循环,(3)再次循环遍历这些核心以确保所有的内容都被处理。

我是否漏掉了什么?对于最简单的情况来说,使用古老的C和OpenMP是否比被宣传为C的最佳替代品的全新Go更好?对于更复杂的例子,如何将一个range分割给多个CPU处理?

英文:

I'm trying to optimise a puzzle with parallel processing, for better performance.

Ideally, in C99 w/ OpenMP, I should be able to do that with the help of a #pragma omp parallel for prior to a for loop in question, and then it should be up to the system to distribute the load between the CPUs.

The official documentation for Go at https://golang.org/doc/effective_go.html#parallel, however, seems to suggest that for parallel processing I must, (0), manually get the number of cores from the runtime environment, (1), loop over said cores, (2), effectively code up a distinct for loop for each core, (3), loop over the cores once again to make sure all the stuff got processed.

Am I missing something? For the simplest case, is OpenMP with the ancient C superior to the brand new Go that's touted as C's best replacement? For a more complicated example, how exactly do you split up a range between the CPUs?

答案1

得分: 6

Effective Go在这方面已经过时了,Go会自动将GOMAXPROCS设置为处理器的数量(你仍然可以手动设置它来强制使用你想要的数量)。

这里有一个非常简单的并行处理切片的示例:

data := make([]float64, SZ)
var wg sync.WaitGroup
for i := range data {
	wg.Add(1)
	go func(v *float64) {
		// 注意,使用rand是一个不好的示例,因为全局rand使用了互斥锁
		*v = rand.Float64()
		wg.Done()
	}(&data[i])
}
wg.Wait()

playground

英文:

Effective Go is outdated about that, Go automatically sets GOMAXPROCS to the number of processors (you can still manually set it to force the number you want).

Here's a very simple example for parallel processing of a slice:

data := make([]float64, SZ)
var wg sync.WaitGroup
for i := range data {
	wg.Add(1)
	go func(v *float64) {
		// note that using rand is a bad example because global rand uses a mutex
		*v = rand.Float64()
		wg.Done()
	}(&data[i])
}
wg.Wait()

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2016年4月30日 07:58:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/36949211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定