分享方式:


如何:在資料管線中使用轉換程式

本主題包含一個基本範例,示範如何在資料管線中使用 並行::transformer 類別。 如需使用資料管線執行影像處理的完整範例,請參閱 逐步解說:建立映射處理網路

資料管道 處理是並行程式設計中的常見模式。 資料管線包含一系列階段,其中每個階段都會執行工作,然後將該工作的結果傳遞至下一個階段。 資料 transformer 管線中索引鍵元件的類別,因為它會收到輸入值、對該值執行工作,然後產生結果供另一個元件使用。

範例

此範例會使用下列資料管線,在初始輸入值下執行一系列轉換:

  1. 第一個階段會計算其輸入的絕對值。

  2. 第二個階段會計算其輸入的平方根。

  3. 第三個階段會計算其輸入的平方。

  4. 第四階段會否定其輸入。

  5. 第五個階段會將最終結果寫入訊息緩衝區。

最後,此範例會將管線的結果列印至主控台。

// 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 專案中,或貼到名為 data-pipeline.cpp 的檔案中,然後在 Visual Studio 命令提示字元視窗中執行下列命令。

cl.exe /EHsc data-pipeline.cpp

另請參閱

非同步代理程式程式庫
非同步訊息區
逐步解說:建立影像處理網路