associative是什么意思?
template<typename Iterator,typename T>
struct accumulate_block
{
void operator()(Iterator first,Iterator last,T& result)
{
result=std::accumulate(first,last,result);
}
};
template<typename Iterator,typename T>
T parallel_accumulate(Iterator first,Iterator last,T init)
{
unsigned long const length=std::distance(first,last);
if(!length) #1
return init;
unsigned long const min_per_thread=25;
unsigned long const max_threads=
(length+min_per_thread-1)/min_per_thread; #2
unsigned long const hardware_threads=
std::thread::hardware_concurrency();
unsigned long const num_threads= #3
std::min(hardware_threads!=0?hardware_threads:2,max_threads);
unsigned long const block_size=length/num_threads; #4
std::vector<T> results(num_threads);
std::vector<std::thread> threads(num_threads-1); #5
Iterator block_start=first;
for(unsigned long i=0;i<(num_threads-1);++i)
{
Iterator block_end=block_start;
std::advance(block_end,block_size); #6
threads[i]=std::thread( #7
accumulate_block<Iterator,T>(),
block_start,block_end,std::ref(results[i]));
block_start=block_end; #8
}
accumulate_block()(block_start,last,results[num_threads-1]); #9
std::for_each(threads.begin(),threads.end(),
std::mem_fn(&std::thread::join)); #10
return std::accumulate(results.begin(),results.end(),init); #11
Before we leave this example, it's worth pointing out that where the addition operator
for the type T is not associative (such as for float or double), the results of this
parallel_accumulate may vary from those of std::accumulate , due to the grouping of
the range into blocks.
《C++ Concurrency in Action》2.4
那句话也有点看不懂。指的是因为运算顺序改变导致的误差么?
------解决方案--------------------
associative 说的是加法的交换率,即 a+b == b+a。
[解决办法]
错了,associative 是加法结合律的意思,即 (a+b)+c == a+(b+c).
由于 float 和 double 精度的问题,这个结合律在计算机里面得不到完美满足,表现之一就是 parallel_accumulate 和 accumulate 对于上述两种类型的数列可能给出不一样的计算结果。