c++ 正在等待与when_all的所有协程

vojdkbi0  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(124)
#include <seastar/core/app-template.hh>
    #include <seastar/core/coroutine.hh>
    #include <seastar/core/sleep.hh>
    #include <seastar/core/when_all.hh>

/*Here I want all the futures to execute*/
    seastar::future<> all_futures()
    {
        seastar::sleep(2s).then([]{std::cout << "2s\n";});
        seastar::sleep(1s).then([]{std::cout << "1s\n";});
        return seastar::sleep(3s).then([]{std::cout << "3s\n";});//CHANGE HERE TO VALUE < 2s
    }
    
    seastar::future<int> get_int()
    {
        std::cout << "Entering winter sleep\n";
        return seastar::sleep(5s).then([]{return 2;}); //CHANGE HERE TO VALUE < 3s
    }
    
    seastar::future<> f_sleeping() {
        std::cout << "Sleeping... " << std::flush;
        using namespace std::chrono_literals;
//Here I want to wait for all the futures and only exit after all futures finished
        return when_all(all_futures(),get_int().then([](const int val){std::cout << "got: " << val << '\n'; })).discard_result();
    }
    
    int main(int argc, char** argv) {
        app_template app;
    
        return app.run(argc, argv, [&app] {
            
            return f_sleeping();
        });
    }

字符串
当运行代码时,一切似乎都按预期工作。但是尝试更改标记为//CHANGE HERE TO VALUE的行中的等待时间,突然不是所有的期货都在等待!所以问题是,如何等待x个期货?另一个问题是,这是库中一个错误,还是仅仅是C++,在这个阶段,它已经成为一种非常古老的技术,在编译过程中无法捕捉到这样的问题?然而,另一个问题是,为什么它编译在所有.我已经看了声明的when_all和显然它接受对迭代器.我不在上面的代码,给予任何iter到该函数,但它编译和运行.作为经常与C++的情况下,不正确,没有给出一个单一的警告.

**编辑|**错误:

错误:无法转换'seastar::when_all(FutOrFuncs&...)[with FutOrFuncs = {seastar::future,seastar::future,seastar::future}](& std::moveseastar::future<&>(one)),( & std::moveseastar::future<&>(three))'从'futurestd::tuple<seastar::future<void,seastar::future,seastar::future >>'到'future' 172| return when_all(std::move(one),std::move(three));|~~|||futurestd::tuple<seastar::future<void,seastar::future,seastar::future >>

pw9qyyiw

pw9qyyiw1#

你只返回了all_futures中的一个future,前两个future被丢弃了,这样就没有办法等待它们了,所以如果没有其他东西像它们一样等待,它们可能会比main活得更久。
如果你真的想等他们,你需要有东西等他们。

seastar::future<> all_futures()
{
    auto two = seastar::sleep(2s).then([]{std::cout << "2s\n";});
    auto one = seastar::sleep(1s).then([]{std::cout << "1s\n";});
    auto three = seastar::sleep(3s).then([]{std::cout << "3s\n";});
    return when_all(std::move(two), std::move(one), std::move(three)).discard_result();
}

字符串

相关问题