4

在 Boost 1.66 上,Asio 已经弃用asio_handler_is_continuationhook 函数,促进了defer函数的使用。似乎该 函数的行为与asio_handler_is_continuation==true 时defer的行为完全相同。post但是,使用方式与使用defer方式不同asio_handler_is_continuation,我不知道如何正确使用defer

编辑:我认为下面的示例过于冗长,无法清楚地表达我的意思。这是较短的示例:

async_read_until(stream, read_buffer, "\r\n", 
    [](boost::system::error_code ec, std::size_t bytes_transferred)
    {
        if(!ec)
            async_write(stream, write_buffer, some_handler);
    })

现在async_read_until完成后,传递的 lambda 处理程序将使用与boost::asio::post. 但是async_write在 lambda 处理程序内部是上一个异步任务的延续,所以我想调用 lambda 处理程序来利用defer优化。

在上面的示例中,有什么方法可以使用defer(而不是post)调用 lambda 处理程序?

原始帖子:我正在尝试编写一个async_echo类似于野兽文档中的简单启动函数,除了调用的部分boost::asio::async_write将被称为延续。为了实现这一点,之前boost::asio::async_read_until的中间操作必须调用处理程序*this作为延续。

这是我在野兽文档的 async_echo 示例中所指的部分:

template<class AsyncStream, class Handler>
void echo_op<AsyncStream, Handler>::
operator()(boost::beast::error_code ec, std::size_t bytes_transferred)
{
    // Store a reference to our state. The address of the state won't
    // change, and this solves the problem where dereferencing the
    // data member is undefined after a move.
    auto& p = *p_;

    // Now perform the next step in the state machine
    switch(ec ? 2 : p.step)
    {
        // initial entry
        case 0:
            // read up to the first newline
            p.step = 1;
            return boost::asio::async_read_until(p.stream, p.buffer, "\r", std::move(*this));

        case 1:
            // write everything back
            p.step = 2;
            // async_read_until could have read past the newline,
            // use buffers_prefix to make sure we only send one line
            return boost::asio::async_write(p.stream,
                boost::beast::buffers_prefix(bytes_transferred, p.buffer.data()), std::move(*this));

        case 2:
            p.buffer.consume(bytes_transferred);
            break;
    }

    // Invoke the final handler. The implementation of `handler_ptr`
    // will deallocate the storage for the state before the handler
    // is invoked. This is necessary to provide the
    // destroy-before-invocation guarantee on handler memory
    // customizations.
    //
    // If we wanted to pass any arguments to the handler which come
    // from the `state`, they would have to be moved to the stack
    // first or else undefined behavior results.
    //
    p_.invoke(ec);
    return;
}

在 1.66 之前的日子里,我可以简单地挂钩函数,如下所示:

template <Function, Handler>
friend bool asio_handler_is_continuation(echo_op<Function, Handler>* handler)
{
    using boost::asio::asio_handler_is_continuation;
    return handler.p_->step == 1 || 
        asio_handler_is_continuation(std::addressof(handler.p_->handler()));
}

echo_op.

从 Boost 1.66 开始,上面的代码不太可能有任何效果(没有BOOST_ASIO_NO_DEPRECATION宏)。所以我应该使用defer.

但是由于boost::asio::async_read_until保证处理程序的调用将以等效于使用 boost::asio::io_context::post(). 的方式执行”,*this因此不会使用 调用defer,即作为延续。

是否有任何解决方法可以boost::asio::async_read_until使用调用处理程序defer?有没有利用defer函数的好例子?

4

3 回答 3

5

这在过去也让我感到困惑。

Executor::defer并且Executor::post两者都执行相同的操作,除了这个注释:

注意:虽然对 defer 的要求与 post 相同,但 post 的使用传达了一种偏好,即调用者不会阻塞 f1 的第一步,而 defer 传达的偏好是调用者会阻塞 f1 的第一步。defer 的一种用途是传达调用者的意图,即 f1 是当前调用上下文的延续。执行器可以使用此信息来优化或以其他方式调整调用 f1 的方式。——尾注

https://www.boost.org/doc/libs/1_67_0/doc/html/boost_asio/reference/Executor1.html

因此,链接延续的责任似乎已成为Executor模型的实现细节。

据我所知,这意味着您需要做的就是调用免费函数defer(executor, handler),执行者将“做正确的事”

更新:

找到一些文档,显示如何通过最终执行程序链接处理程序:

文档来源:https ://github.com/chriskohlhoff/asio-tr2/blob/master/doc/executors.qbk

示例:https ://github.com/chriskohlhoff/executors/blob/v0.2-branch/src/examples/executor/async_op_2.cpp

请参阅 async_op_2.cpp 中的第 38 行以上

于 2018-05-04T14:41:09.817 回答
2

在玩了一会儿之后,事实证明它asio_handler_is_continuation并没有被弃用;并且没有办法用defer当前替换它。

post要将任何调用重定向到defer,我提供了以下自定义执行程序:

template<typename UnderlyingExecutor, typename std::enable_if<boost::asio::is_executor<UnderlyingExecutor>::value, int>::type = 0>
class continuation_executor
{
    private:
        UnderlyingExecutor _ex;

    public:

        continuation_executor(UnderlyingExecutor ex)
            :_ex(ex){}

        template<class Function, class Allocator>
        void post(Function f, Allocator a)
        {
            std::cout<<"Redirected to defer()"<<std::endl;
            _ex.defer(BOOST_ASIO_MOVE_CAST(Function)(f),a);
        }

        template<class Function, class Allocator>
        void defer(Function f, Allocator a)
        {
            std::cout<<"defer() called"<<std::endl;
            _ex.defer(BOOST_ASIO_MOVE_CAST(Function)(f),a);
        }

        template<class Function, class Allocator>
        void dispatch(Function f, Allocator a)
        {
            std::cout<<"dispatch() called"<<std::endl;
            _ex.dispatch(BOOST_ASIO_MOVE_CAST(Function)(f),a);
        }

        auto context() -> decltype(_ex.context())
        {
            return _ex.context(); 
        }

        void on_work_started()
        {
            _ex.on_work_started();
        }
        void on_work_finished()
        {
            _ex.on_work_finished();
        }
};

它实际上是一个微不足道的 executor,完全依赖于底层 executor,并continuation_executor::post重定向到底层 executor 的defer.

但是当我将处理程序传递给async_read_some类似的东西时bind_executor(conti_exec, handler),我得到以下输出:

dispatch() called

所以传递的处理程序不会通过post(); 它是通过其他方式安排的。具体来说,内置异步函数,如asio::async_read_some通过 调度内部操作对象scheduler::post_immediate_completion,然后io_context::run执行操作。

异步操作完成后,complete调用操作对象的方法来执行用户提供的处理程序。该complete方法,至少在当前实现中,使用关联的执行程序的dispatch方法来运行处理程序。上面的钩子没有地方。所以它完全过时了;尝试使用defer而不是asio_handler_is_continuation运气不好。

我在我的问题中所说的,“从 Boost 1.66 开始,上面的代码不太可能有任何效果(没有 BOOST_ASIO_NO_DEPRECATION 宏)。”,是完全错误的。asio_handler_is_continuation仍然有效,并且从 1.67 开始不被弃用

asio_handler_is_continuation是仍然有效的证据:

  // Start an asynchronous send. The data being sent must be valid for the
  // lifetime of the asynchronous operation.
  template <typename ConstBufferSequence, typename Handler>
  void async_send(base_implementation_type& impl,
      const ConstBufferSequence& buffers,
      socket_base::message_flags flags, Handler& handler)
  {
    bool is_continuation =
      boost_asio_handler_cont_helpers::is_continuation(handler);

    // Allocate and construct an operation to wrap the handler.
    typedef reactive_socket_send_op<ConstBufferSequence, Handler> op;
    typename op::ptr p = { boost::asio::detail::addressof(handler),
      op::ptr::allocate(handler), 0 };
    p.p = new (p.v) op(impl.socket_, impl.state_, buffers, flags, handler);

    BOOST_ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket",
          &impl, impl.socket_, "async_send"));

    start_op(impl, reactor::write_op, p.p, is_continuation, true,
        ((impl.state_ & socket_ops::stream_oriented)
          && buffer_sequence_adapter<boost::asio::const_buffer,
            ConstBufferSequence>::all_empty(buffers)));
    p.v = p.p = 0;
  }

请注意,它用于boost_asio_handler_cont_helpers确定处理程序是否继续。boost_asio_handler_cont_helpers内部调用asio_handler_is_continuation.

async_sendasync_write_some内部使用。我没有检查 asio 库提供的每个内置异步任务,但我很确定其他异步任务以相同的方式执行它的处理程序。

因此,如果您希望内置异步任务作为延续执行您的处理程序,您将不得不依赖asio_handler_is_continuation. defer不会完全取代它!defer只能在您直接从代码中安排处理程序时使用。

于 2018-05-05T10:58:58.667 回答
1

似乎,在https://github.com/chriskohlhoff/asio-tr2/blob/master/doc/executors.qbkdispatch()上找到的代码中的注释实际上包含关于和post()的最详细描述defer()

defer()将新创建的作业的处理推迟到当前作业完成之后。它不会其推迟到其他排队的作业之后。在当前作业完成后推迟有很大的优势,新作业可以在与当前作业相同的线程中运行。默认执行程序将尝试这样做。由于新作业很可能会使用当前作业中的一些或更多数据,因此保持在同一个线程中并因此保持相同的 CPU 内核极大地提高了缓存局部性,从而减少了总执行时间并提高了吞吐量。

换句话说:在您的完成处理程序/任务中,恰好启动一个新的完成处理程序/任务,您几乎总是希望defer()使用post(). 如果新任务在当前任务结束时启动,则尤其如此。

但是,那些启动多个新任务的任务应该只通过 提交最相关的任务(通常是最后一个任务)defer(),并post()用于所有其他任务。

仅对于那些非常简单的任务,考虑通过dispatch()而不是post()or提交它们queue():如果规则允许(例如它们被分派到的链,当前有一个空队列),那么它们将直接运行,避免所有排队和取消排队延迟。

于 2021-09-11T14:55:18.247 回答