简体   繁体   English

使用C ++ 11异步功能的管道数据流

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

I'm trying to implement a multithreaded pipeline dataflow framework with the following features: 我正在尝试实现具有以下功能的多线程管道数据流框架:

  1. The pipeline can be described as an acyclic directed graph. 管道可以描述为非循环有向图。 Each node performs some processing and has arbitrary number of inputs of arbitrary types and one output of arbitrary type. 每个节点执行一些处理,并具有任意数量的任意类型的输入和一个任意类型的输出。

  2. For each given input data instance each node should be executed not more that once, after that the result should be cached. 对于每个给定的输入数据实例,每个节点应执行一次以上,然后将结果缓存。 Although this cache shouldn't persist in memory longer that required and should be deleted when no longer needed by any other nodes. 尽管此高速缓存不应在内存中保留的时间更长,而应在其他任何节点不再需要时将其删除。

  3. Each node should support lazy evaluation, ie should be executed only at the moment it's output is needed by some another node. 每个节点都应支持惰性评估,即仅应在另一个节点需要其输出时执行。

Is it possible to implement this by using C++11 multithreading features, especially std::future , std::promise and std::async ? 是否可以通过使用C ++ 11多线程功能来实现这一点,尤其是std::futurestd::promisestd::async Can anybody give a clue? 有人可以提供线索吗?

I believe it actually is fairly trivial using an async framework. 我相信使用async框架实际上并不容易。

If you look at std::launch you will realize there is a deferred mode: 如果您看一下std :: launch,您将意识到有一个延迟模式:

  • std::launch::deferred : the task is executed on the calling thread the first time its result is requested (lazy evaluation) std::launch::deferred :任务在第一次请求其结果时在调用线程上执行(延迟评估)

Thus, you can launch a task and have it executed only when the result is needed. 因此,您可以启动任务并仅在需要结果时才执行它。 However, since you mention an acyclic graph, you probably want to share the result: a std::future (as returned by a call to std::async ) cannot be shared; 但是,由于提到了一个非循环图,因此您可能希望共享结果:无法共享std::future (由对std::async的调用返回)。 you need a std::shared_future for this. 为此,您需要一个std::shared_future

And thus, putting it altogether: 因此,将其放在一起:

// 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