对一个数组并行求和
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()
然后,如果使用原子整数,可以更有效地自动更改整数的值。
最后,当单个工作负载很小或非常可预测时,考虑批处理,以减少同步的开销。
相关文章:
- 并行用于C++17中数组索引范围内的循环
- OpenMP:并行更新数组总是需要减少数组吗
- 遍历并行数组以确定C++中的最大数字
- 排序并行数组
- 如何从具有两列的.txt文件创建并行数组?
- 是否可以在并行区域中为共享 2D 数组创建选定元素的线程本地副本?(共享,私有,障碍:OPenMP)
- 为什么并行读取数组会导致内存泄漏?
- C++赋值简介:并行数组
- 如何解决在使用动态 2D 数组进行矩阵乘法的 MPI 进行并行编程时的问题
- 循环函数中的并行数组
- 在OpenMP上的并行合并排序上的数组大小问题.如何将合并分类分类为更多任务
- 使用getline从文本文件中创建2个并行字符串数组
- 对于循环和并行数组:未声明的标识符
- 如何使用并行数组使用 c++ 制作包含数量和单词的列表
- 数组的并行求和比C++中的顺序求和慢
- 对一个具有重复元素的数组进行排序时更新并行数组
- 将2D数组行存储在并行数组中
- 将并行数组与 txt 文件分开
- 如何并行删除数组中的零值
- 需要帮助解决特征数组并行构造中的数据争用