簡體   English   中英

使用C ++ 11異步功能的管道數據流

[英]Pipeline dataflow using C++11 async features

我正在嘗試實現具有以下功能的多線程管道數據流框架:

  1. 管道可以描述為非循環有向圖。 每個節點執行一些處理,並具有任意數量的任意類型的輸入和一個任意類型的輸出。

  2. 對於每個給定的輸入數據實例,每個節點應執行一次以上,然后將結果緩存。 盡管此高速緩存不應在內存中保留的時間更長,而應在其他任何節點不再需要時將其刪除。

  3. 每個節點都應支持惰性評估,即僅應在另一個節點需要其輸出時執行。

是否可以通過使用C ++ 11多線程功能來實現這一點,尤其是std::futurestd::promisestd::async 有人可以提供線索嗎?

我相信使用async框架實際上並不容易。

如果您看一下std :: launch,您將意識到有一個延遲模式:

  • std::launch::deferred :任務在第一次請求其結果時在調用線程上執行(延遲評估)

因此,您可以啟動任務並僅在需要結果時才執行它。 但是,由於提到了一個非循環圖,因此您可能希望共享結果:無法共享std::future (由對std::async的調用返回)。 為此,您需要一個std::shared_future

因此,將其放在一起:

// Disclaimer:
// Compiles but does not run, but I have not figured it out.
// See: http://ideone.com/XZ49Dg

#include <future>
#include <iostream>

int main() {
    std::shared_future<std::string> greeting = std::async(std::launch::deferred, []() {
        std::string s;
        std::cout << "Enter how you would like to be greeted: ";
        std::getline(std::cin, s);
        return s;
    });

    std::shared_future<int> choice = std::async(std::launch::deferred, []() {
        int c = 0;
        std::cout << "Pick any integer: ";
        std::cin >> c;
        return c;
    });

    std::shared_future<void> complete = std::async(std::launch::deferred, [=]() mutable {
        std::string const g = greeting.get();
        int const c = choice.get();

        std::cout << "Hello " << g << ", you picked " << c << "!\n";
    });

    complete.wait();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM