编译下面的程序时,我收到错误消息:
错误 1 错误 C2228: '.get_future' 左侧必须有类/结构/联合 c:\users\haliaga\documents\visual studio 2010\projects\test\test\accumulateexceptionsafe.cpp 62 1 测试
这实际上不是真正的问题。
如果您评论这些行:
//futures[i]=task.get_future();
//threads[i]=std::thread(std::move(task),block_start,block_end);
//block_start=block_end;
你会得到下面的警告,说“task”没有被调用:
*警告 C4930: 'std::packaged_task<> task(accumulate_block (__cdecl )(void))': 未调用原型函数(是否打算定义变量?) 1> with 1> [ 1> =int (std::_List_iterator >>,std::_List_iterator>>), 1> 迭代器=std::_List_iterator>>, 1> T=int 1> ]
什么是指定的正确方法:
std::packaged_task<T(Iterator,Iterator)> task(accumulate_block<Iterator,T>());
?
谢谢
PS:找到下面的代码:
#include <list>
#include <numeric>
#include <vector>
#include <thread>
#include <future>
using namespace std;
template<typename Iterator,typename T>
struct accumulate_block
{
T operator()(Iterator first, Iterator last)
{
std::thread::id id = std::this_thread::get_id();
return std::accumulate(first, last, T());
}
};
class join_threads
{
std::vector<std::thread>& threads;
public:
explicit join_threads(std::vector<std::thread>& threads_):
threads(threads_)
{
std::thread::id id = std::this_thread::get_id();
}
~join_threads()
{
std::thread::id id = std::this_thread::get_id();
for(unsigned long i=0;i<threads.size();++i)
{
if(threads[i].joinable())
threads[i].join();
}
}
};
template<typename Iterator,typename T>
T parallel_accumulate(Iterator first,Iterator last,T init)
{
std::thread::id id = std::this_thread::get_id();
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<std::future<T> > futures(num_threads-1);
std::vector<std::thread> threads(num_threads-1);
join_threads joiner(threads);
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);
std::packaged_task<T(Iterator,Iterator)> task(accumulate_block<Iterator,T>());
futures[i]=task.get_future();
threads[i]=std::thread(std::move(task),block_start,block_end);
block_start=block_end;
}
T last_result=accumulate_block<Iterator, T>()(block_start,last);
T result=init;
for(unsigned long i=0;i<(num_threads-1);++i)
{
result+=futures[i].get();
}
result += last_result;
return result;
};
int main()
{
list<int> l;
for(int i=0; i<26; ++i)
l.push_back(i);
std::thread::id id = std::this_thread::get_id();
int res = ::parallel_accumulate(l.begin(), l.end(), 0);
return 0;
}