作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
在下面的示例(第 2 章)中,Anthony Williams 试图并行化标准的 accumulate 函数。我的问题是他为什么要这样做:
unsigned long const max_threads=(length+min_per_thread-1)/min_per_thread;
为什么加长度减1?为什么不只是:
unsigned long const max_threads=length/min_per_thread;
................................................ .....................................
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)
return init;
unsigned long const min_per_thread=25;
unsigned long const max_threads=(length+min_per_thread-1)/min_per_thread;
unsigned long const hardware_threads=std::thread::hardware_concurrency();
unsigned long const num_threads=
std::min(hardware_threads!=0?hardware_threads:2,max_threads);
unsigned long const block_size=length/num_threads;
std::vector<T> results(num_threads);
std::vector<std::thread> threads(num_threads-1);
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( accumulate_block<Iterator,T>(),
block_start,block_end,std::ref(results[i]));
block_start=block_end;
}
accumulate_block()(block_start,last,results[num_threads-1]);
std::for_each(threads.begin(),threads.end(),
std::mem_fn(&std::thread::join));
return std::accumulate(results.begin(),results.end(),init);
}
最佳答案
使用的问题
unsigned long const max_threads=length/min_per_thread;
是由整数除法时使用的截断舍入引起的
如果
length = 7
min_per_thread = 5
然后
max_threads = length / min_per_thread = 1
虽然最大线程实际上应该是 2
length + min_per_thread - 1 = 11
max_threads = (length + min_per_thread - 1) / min_per_thread = 2
关于c++ - C++ Concurrency in action 中关于 parallel_accumulate 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1419314/
在下面的示例(第 2 章)中,Anthony Williams 试图并行化标准的 accumulate 函数。我的问题是他为什么要这样做: unsigned long const max_thr
我是一名优秀的程序员,十分优秀!