摘自 http://msdn.microsoft.com/zh-cn/library/dd728076(v=vs.110).aspx
本主题包含一个基本示例,演示如何使用 concurrency::transformer 数据管道中的类。 有关使用数据管道执行图像处理操作的更完整示例,请参见演练:创建图像处理网络。
“数据管道”是并发编程中的常见模式。 数据管道由一系列阶段组成,其中每个阶段执行工作,然后将该工作的结果传递到下一阶段。 transformer 类是数据管道中的一个关键组件,因为它接收输入值,对该值进行处理,然后生成供另一个组件使用的结果。
该示例使用以下数据管道执行一系列的给定初始输入值的转换:
-
第一个阶段计算其输入的绝对值。
-
第二个阶段计算其输入的平方根。
-
第三个阶段计算其输入的平方。
-
第四个阶段对其输入求反。
-
第五个阶段将最终结果写入消息缓冲区。
最后,该示例将管道的结果输出到控制台。
// data-pipeline.cpp // compile with: /EHsc #include <agents.h> #include <math.h> #include <iostream> using namespace concurrency; using namespace std; int wmain() { // Computes the absolute value of its input. transformer<int, int> t0([](int n) { return abs(n); }); // Computes the square root of its input. transformer<int, double> t1([](int n) { return sqrt(static_cast<double>(n)); }); // Computes the square its input. transformer<double, int> t2([](double n) { return static_cast<int>(n * n); }); // Negates its input. transformer<int, int> t3([](int n) { return -n; }); // Holds the result of the pipeline computation. single_assignment<int> result; // Link together each stage of the pipeline. // t0 -> t1 -> t2 -> t3 -> result t0.link_target(&t1); t1.link_target(&t2); t2.link_target(&t3); t3.link_target(&result); // Propagate a message through the pipeline. send(t0, -42); // Print the result to the console. wcout << L"The result is " << receive(result) << L'.' << endl; }
该示例产生下面的输出:
The result is -42.
数据管道中的阶段通常输出一个其类型不同于输入值类型的值。 在该示例中,第二个阶段采用 int 类型的值作为其输入值,并生成该值的平方根 (double) 作为其输出。
![]() |
---|
此示例中的数据管道用于说明。 因为每项转换操作都很少工作,所以执行消息传递任务所需的开销会超过使用数据管道带来的好处。 |