我有以下算法总结数组的元素:总结阵列并联
// 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。话又说回来
// 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完成:
根本不使用线程。你正在杀死性能。而每元素锁定只会让它变得更糟。 –
所以,你想通过使用多个线程来总结单个数组的所有元素? – FrankS101