FastFlow(5)---软件加速器 software accelerator
FastFlow可以用来对顺序执行的代码进行加速而不需要整体重构程序架构。程序员本人需要识别那些需要加速执行。
FastFlow加速概念设计图如下,
下面是一个并行计算立方x3的例子,
#include <vector>
#include <ff/farm.hpp>
#include <iostream>
using namespace ff;
struct Worker : ff_node_t<long> {
long *svc(long *task) {
*task = pow(*task, 3);
return task;
}
};
int main(int argc, char *argv[]) {
assert(argc > 2);
int nworkers = atoi(argv[1]);
int streamlen = atoi(argv[2]);
std::vector<std::unique_ptr<ff_node> > Workers;
for (int i = 0; i < nworkers; ++i)
Workers.push_back(make_unique<Worker>());
ff_Farm<long> farm(std::move(Workers),true); // turn on the accelerator mode
if (farm.run_then_freeze() < 0) error("running farm"); //run the accelerator asynchronously
long *result = nullptr;
for (long i = 0; i < streamlen; i++){
long *task = new long(i);
farm.offload(task); //offload the computing onto the farm
for (volatile long k = 0; k < 10000; ++k); //do something smart here, reserved
if (farm.load_result_nb(result)) {
std::cerr << "[inside for loop] result= " << *result << "\n";
delete result;
}
}
farm.offload(EOS); //sending the End of Stream
#if 1
while(farm.load_result(result)){
std::cerr << "[outside for loop] result = " << *result << "\n";
delete result;
}
#else
do{
if (farm.load_result_nb(result)){
if (result == EOS) break;
std::cerr << "[outside for loop] result = " << *result << "\n";
delete result;
}
}while (1)
#endif
farm.wait(); //wait for termination
return 0;
}
运行结果: