这是对问题进行多线程集成的源代码。
#include <vector>
#include <memory>
#include <future>
#include <iterator>
#include <iostream>
struct sample {
double duration;
double value;
};
typedef std::pair<sample*, sample*> data_range;
sample* begin( data_range const& r ) { return r.first; }
sample* end( data_range const& r ) { return r.second; }
typedef std::unique_ptr< std::future< double > > todo_item;
double integrate( data_range r ) {
double total = 0.;
for( auto&& s:r ) {
total += s.duration * s.value;
}
return total;
}
todo_item threaded_integration( data_range r ) {
return todo_item( new std::future<double>( std::async( integrate, r )) );
}
double integrate_over_threads( data_range r, std::size_t threads ) {
if (threads > std::size_t(r.second-r.first))
threads = r.second-r.first;
if (threads == 0)
threads = 1;
sample* begin = r.first;
sample* end = r.second;
std::vector< std::unique_ptr< std::future< double > > > todo_list;
sample* highwater = begin;
while (highwater != end) {
sample* new_highwater = (end-highwater)/threads+highwater;
--threads;
todo_item item = threaded_integration( data_range(highwater, new_highwater) );
todo_list.push_back( std::move(item) );
highwater = new_highwater;
}
double total = 0.;
for (auto&& item: todo_list) {
total += item->get();
}
return total;
}
sample data[5] = {
{1., 1.},
{1., 2.},
{1., 3.},
{1., 4.},
{1., 5.},
};
int main() {
using std::begin; using std::end;
double result = integrate_over_threads( data_range( begin(data), end(data) ), 2 );
std::cout << result << "\n";
}
它需要一些修改才能以您指定的格式读取数据。
但是你可以用std::thread::hardware_concurrency()
线程数来调用它,它应该可以工作。
(特别是,为了简单起见,我有成对的 (duration, value) 而不是 (time, value),但这只是一个小细节)。