我相信使用async
框架实际上是相当微不足道的。
如果你看一下std::launch你会发现有一个延迟模式:
std::launch::deferred
:任务在第一次请求结果时在调用线程上执行(惰性求值)
因此,您可以启动任务并仅在需要结果时才执行它。但是,由于您提到了一个无环图,您可能希望共享结果:a 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();
}