我有以下算法總結數組的元素:總結陣列並聯
// 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