【发布时间】:2016-09-15 20:35:25
【问题描述】:
我有以下算法对数组元素求和:
// 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。
【问题讨论】:
-
完全不要使用线程。你正在扼杀表演。并且每个元素的锁定只会让它变得更糟。
-
那么,你想用多个线程对单个数组的所有元素求和吗?
标签: c++ multithreading concurrency mutex