首页 文章

并行汇总数组

提问于
浏览
0

我有以下算法来总结数组的元素:

// 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 .

1 回答

  • 0

    在释放锁之前递增 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,则可以更有效地以原子方式更改整数的值 .

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

相关问题