1

I'd like to serialize http post requests using strand, to avoid overlapping writes to network.

My approach was to call the post method from the strand object with the callback that send the data as can be shown in the following code :

void Send(
   boost::beast::http::request<boost::beast::http::string_body> &req) {
  strand_.post([=]() {
      ...
      boost::beast::http::write(stream_, req);
      ...
  }

However, from looking at some examples, I've noticed 2 types of strand definitions :

boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::asio::io_context::strand strand_;

Any idea what's the different between each type ?

Zohar81
  • 4,554
  • 5
  • 29
  • 82

1 Answers1

2

There's actually not much difference between them. In fact, they share a lot of code and that shows that one was created from the other.

See diff here (bosst 1.67).

However, boost::asio::strand es a class template originally intended to be used with asio::io_service:

template <typename Executor>;
class strand
{
public:
  /// The type of the underlying executor.
  typedef Executor inner_executor_type;

  /// Default constructor.
  /**
   * This constructor is only valid if the underlying executor type is default
   * constructible.
   */
  strand()
    : executor_(),
      impl_(use_service<detail::strand_executor_service>(
            executor_.context()).create_implementation())
  {
  }

The class boost::asio::io_context::strand is not a class template and is bound to the class boost::asio::io_context:

class io_context::strand
{
public:
  /// Constructor.
  /**
   * Constructs the strand.
   *
   * @param io_context The io_context object that the strand will use to
   * dispatch handlers that are ready to be run.
   */
  explicit strand(boost::asio::io_context&amp; io_context)
    : service_(boost::asio::use_service&lt;
        boost::asio::detail::strand_service&gt;(io_context))
  {
    service_.construct(impl_);
  }
ichramm
  • 6,437
  • 19
  • 30
  • Hi and thanks for the help. However, I'm still confused which type to use for my need to serialize http writes. Perhaps you can elaborate on this ? – Zohar81 Sep 30 '21 at 18:21
  • Considering that both are fairly similar, I would go with `boost::asio::io_context::strand` because it is explicitly designed for `boost::asio::io_context`. – ichramm Sep 30 '21 at 21:09