HOW TO:在資料管線中使用轉換程式
本主題包含基本範例,其中會示範如何使用 concurrency::transformer 資料管線中的類別。如需使用資料管線平行執行影像處理的更完整的範例,請參閱逐步解說:建立影像處理網路。
「資料管線」(Data Pipelining) 是並行程式設計中常見的模式。資料管線是由一系列的階段所組成,其中每個階段分別會執行工作,然後將該工作的結果傳遞至下一個階段。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) 做為其輸出。
![]() |
---|
這個範例中的資料管線僅供舉例之用。因為每個轉換作業執行少量工作,執行訊息傳遞所需的額外負荷可能大於使用資料管線的好處。 |
編譯程式碼
將範例程式碼複製並貼上它在 Visual Studio 專案中,或將它貼在檔名為資料 pipeline.cpp ,然後執行下列命令,Visual Studio 的命令提示字元] 視窗中。
cl.exe /EHsc data-pipeline.cpp