使用seastar库由fn arg引起的段错误

问题描述 投票:0回答:1

在下面的代码中,如果我使用名为 chunk 的本地变量,该程序将按预期工作,但如果我使用相同的变量类型但作为 fn arg 传递,则会出现段错误。 我正在移动这些物体,所以应该不会有问题。

#include <seastar/core/app-template.hh>
#include <seastar/util/log.hh>
#include <seastar/core/coroutine.hh>
#include <seastar/core/sleep.hh>
#include <seastar/coroutine/maybe_yield.hh>
#include <seastar/coroutine/generator.hh>
#include <seastar/core/circular_buffer.hh>
#include <seastar/coroutine/all.hh>
#include <seastar/core/when_all.hh>
#include <seastar/core/reactor.hh>
#include <seastar/coroutine/parallel_for_each.hh>
#include <seastar/core/do_with.hh>

#include <stdexcept>
#include <vector>
#include <iostream>
#include <chrono>
#include <seastar/core/circular_buffer.hh>
#include <seastar/core/sleep.hh>
#include <seastar/coroutine/generator.hh>
#include <ranges>

seastar::coroutine::experimental::generator<char, seastar::circular_buffer>
generate_chars(coroutine::experimental::buffer_size_t, std::vector<char>&& buf) {
                std::ranges::sort(buf,ranges::greater());
    while (std::size(buf)) {
        char some_char = buf.back();
        buf.pop_back();
        co_yield some_char;
    }
}

future<> print_generated_chars(vector<char>&& chunk_)//instead of fn arg (which crashes) use local var chunk
{
    std::vector<char> chunk{'1','8','7','6','5','4','3','2'};//this will not cause segfault
    auto char_generator = generate_chars(coroutine::experimental::buffer_size_t{5},std::move(chunk));
    while (std::optional<char> c = co_await char_generator())
    {
        std::cout << "char: " << c.value() << '\n';
    }
}

int main(int argc, char** argv) {
    app_template app;

    return app.run(argc, argv, [&app] {
        
        std::vector<char> buf_1{'1','8','7','6','5','4','3','2'};
        return print_generated_chars(std::move(buf_1));
    });
}
c++ asynchronous seastar
1个回答
0
投票

我无法将代码发布到评论中,所以让我在这里展示一下。

我从未使用过协同例程,我不知道对象生命周期在这方面是如何工作的。也许存在细微差别。如果你说本地向量有效,请尝试将代码更改为以下方式:

future<> print_generated_chars(vector<char>&& chunk)
{
    auto local_chunk = std::move(chunk);

    auto char_generator = generate_chars(
       coroutine::experimental::buffer_size_t{5},
       std::move(local_chunk));

    while (std::optional<char> c = co_await char_generator())
    {
        std::cout << "char: " << c.value() << '\n';
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.