并行总结一个数组

Summing up an array in parallel

我有以下算法来求和数组的元素:

// global
index = 0
array = [...]
total_sum = 0 // this is what we're interested in

// per thread
thread_sum = 0
mutex.lock()
while (index < array.size) {
  mutex.unlock()

  thread_sum += array[index]

  mutex.lock()
  index++
}
total_sum += thread_sum
mutex.unlock()

每个线程都运行相同的代码,并且它们在完成后立即与主线程连接。问题是有时不止一个线程添加相同的数字。这是怎么发生的?

原始代码在 C++ 中并使用 std::vector/thread/mutex/ref。

在释放锁之前增加index,否则多个线程可能会看到相同的值:

// per thread
thread_sum = 0
mutex.lock()
while (index < array.size) {
  i = index++
  mutex.unlock()

  thread_sum += array[i]

  mutex.lock()
}
total_sum += thread_sum
mutex.unlock()

然后,如果您使用 atomic integers.

,则可以更有效地以原子方式更改整数的值

最后考虑在单个工作负载较小或非常可预测时进行批处理,以减少同步开销。