TBB管道库的输入过滤器指南 在我以前的问题中,我用C++(Linux)实现了TBB流水线,输入、转换和输出过滤器:
输入过滤器从文本文件中读取数据(C结构),并传递给转换过滤器。转换过滤器正在更新数据并将其传递给输出过滤器。输出筛选器正在将其存储回光盘。一个简单的读写应用程序 现在,我希望创建一个主应用程序。主应用程序将创建一个TBB管道,开始时有三个过滤器:TBB管道库的输入过滤器指南 在我以前的问题中,我用C++(Linux)实现了TBB流水线,输入、转换和输出过滤器:,c++,multithreading,parallel-processing,intel,tbb,C++,Multithreading,Parallel Processing,Intel,Tbb,输入过滤器从文本文件中读取数据(C结构),并传递给转换过滤器。转换过滤器正在更新数据并将其传递给输出过滤器。输出筛选器正在将其存储回光盘。一个简单的读写应用程序 现在,我希望创建一个主应用程序。主应用程序将创建一个TBB管道,开始时有三个过滤器: InputFilter:从主应用程序接收数据/C结构并将其传递 TransformFilter:进行一些处理 OutputFilter:接收它并将信息返回到主应用程序 在开始时,InputFilter将不执行任何操作,因为data/C结构将为空。因此,
我修改了页面中的示例,以便将第一个过滤器设置为线程绑定。它运行良好,我认为这正是您所需要的:
#include <iostream>
#include "tbb/compat/thread"
#include "tbb/pipeline.h"
using namespace tbb;
using namespace std;
char InputString[] = "abcdefg\n";
class InputFilter: public thread_bound_filter {
char* my_ptr;
public:
void* operator()(void*) {
if (*my_ptr)
return my_ptr++;
else
return NULL;
}
InputFilter()
: thread_bound_filter( serial_in_order ), my_ptr(InputString)
{}
};
class OutputFilter: public filter {
public:
void* operator()(void* item) {
std::cout << *(char*)item;
return NULL;
}
OutputFilter() : filter(serial_in_order) {}
};
void RunPipeline(pipeline* p) {
p->run(8);
}
int main() {
// Construct the pipeline
InputFilter f;
OutputFilter g;
pipeline p;
p.add_filter(f);
p.add_filter(g);
// Another thread initiates execution of the pipeline
thread t(RunPipeline, &p);
// Process the thread_bound_filter with the current thread.
while (f.process_item()!=thread_bound_filter::end_of_stream)
continue;
// Wait for pipeline to finish on the other thread.
t.join();
return 0;
}
#包括
#包括“tbb/兼容/线程”
#包括“tbb/pipeline.h”
使用名称空间tbb;
使用名称空间std;
char InputString[]=“abcdefg\n”;
类InputFilter:公共线程\u绑定\u筛选器{
char*my_ptr;
公众:
void*运算符()(void*){
如果(*我的ptr)
返回我的_ptr++;
其他的
返回NULL;
}
InputFilter()
:线程绑定过滤器(串行顺序)、我的ptr(输入字符串)
{}
};
类OutputFilter:公共筛选器{
公众:
void*运算符()(void*项){
标准:不能运行(8);
}
int main(){
//建设管道
输入滤波器f;
输出滤波器g;
管道p;
p、 添加_过滤器(f);
p、 添加_过滤器(g);
//另一个线程启动管道的执行
螺纹t(管路和管道);
//使用当前线程处理线程绑定过滤器。
while(f.进程\u项()!=线程\u绑定的\u过滤器::结束\u流)
继续;
//等待管道在另一个线程上完成。
t、 join();
返回0;
}
当然,您可能需要添加更多筛选器,更改其类型(第一个必须是串行的除外),更改令牌的数量,使用
task::enqueue()
而不是显式线程,用try\u process\u item()替换process\u item()
为了避免在令牌数量超过时被阻塞。但总体思路是一样的,您可以将控件返回到处理筛选器的线程。您好。非常感谢。我有了一些想法。我对线程概念有点陌生。我尝试了代码,它正在工作。如果您能多帮我一点,我不能真正理解abt显式线程和任务队列的使用。我想从主应用程序中逐个发送一个字符到输入筛选器。你能帮我一下吗。非常感谢。.线程绑定筛选器的思想是只有[try_]process_item()调用它。因此,当你从main()调用f.process_item()时
,您最终会在同一线程上调用InputFilter。因此,该示例执行了您所说的操作—它将字符从主线程一个接一个地(每个process\u item()
call)发送到其他线程处理的下一个过滤器。