2016-09-15 144 views
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。话又说回来

// 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完成:

+1

根本不使用线程。你正在杀死性能。而每元素锁定只会让它变得更糟。 –

+0

所以,你想通过使用多个线程来总结单个数组的所有元素? – FrankS101

回答

0

增量您解除锁定前index,否则多线程可能会看到相同的值。

最后在个别工作负载很小或非常可预测时减少同步开销时考虑批处理。

+0

我在重新锁定之后递增索引。这不够好吗?有什么不同? – adrianton3

+0

在循环体内的线程重新锁定之前,另一个线程可能会获得锁并以相同的值输入循环体。 – BeyelerStudios