jjzjj

c++ - 为什么没有 strand::wrap() 等同于 strand::post()?

coder 2024-02-24 原文

strand::wrap() 的行为被定义为它创建一个仿函数,该仿函数将在调用时执行 strand::dispatch()。我最近在我们的一个执行以下序列的应用程序中遇到了一个错误:

my_great_function(..., s.wrap(a), s.wrap(b));

应用程序保证 s.wrap(a) 创建的仿函数在 s.wrap(b) 之前被调用。但是,存在竞争条件,第一个仿函数在链外调用,因此延迟调用,而第二个仿函数在链内部调用并立即执行。这违反了应用程序的 ab 之前的排序假设,并导致未定义的行为。

使用 strand::post() 而不是 strand::dispatch() 是解决这个问题的一种方法,但是没有简单的方法可以像使用 strand.wrap()。我可以创建辅助函数来通过 strand 发布,我想知道是否有更简单的方法?

最佳答案

关于为什么 strand.poststrand.wrap 不存在的纯粹猜测:

  • 我找不到任何人正式提出在功能请求中需要等效的 strand.wrap() 的案例。
  • 基于 strand.wrap() 最常见的用法,它很可能根据 strand.dispatch() 来实现,以优化组合操作的中间处理程序。可以在满足完成条件后立即调用用户的完成处理程序,而不必为延迟调用发布完成处理程序。

最简单的解决方案可能是将链与 ab 处理程序一起传递给 my_great_function。如果 my_great_function 需要特定的处理程序调用顺序,那么让 my_great_function 保证顺序似乎是可以接受的,而不是将责任传递给调用者,这可能会忽略必要的订购。另一方面,如果 my_great_function 相当通用,处理程序之间需要特定的调用顺序,则考虑将处理程序一起传递到一个结构中,该结构直接或间接暗示排序,例如 std::tuple.

虽然这些解决方案都没有提供一般可重用的解决方案,但它可能是最简单的解决方案。除了提供 asio_handler_invoke 之外,官方支持的解决方案是使用自定义处理程序类型。通过 ADL 可用的功能考虑操作的中间和完成处理程序。这是一个主要基于 detail/wrapped_handler.hpp 的完整示例:

#include <iostream>

#include <boost/asio.hpp>

/// @brief Custom handler wrapper type that will post into its dispatcher.
template <typename Dispatcher,
          typename Handler>
class post_handler
{
public:
  typedef void result_type;

  post_handler(Dispatcher dispatcher, Handler handler)
    : dispatcher_(dispatcher),
      handler_(handler)
  {}

  void operator()()
  {
    dispatcher_.post(handler_);
  }

  template <typename Arg1>
  void operator()(Arg1 arg1)
  {
    dispatcher_.post(boost::bind(handler_, arg1));
  }

  template <typename Arg1, typename Arg2>
  void operator()(Arg1 arg1, Arg2 arg2)
  {
    dispatcher_.post(boost::bind(handler_, arg1, arg2));
  }

  Dispatcher dispatcher_;
  Handler handler_;
};

// Custom invocation hooks for post_handler.  These must be declared in 
// post_handler's associated namespace for proper resolution.

template <typename Function, typename Dispatcher, typename Handler>
inline void asio_handler_invoke(Function& function,
    post_handler<Dispatcher, Handler>* this_handler)
{
  this_handler->dispatcher_.post(
      boost::asio::detail::rewrapped_handler<Function, Handler>(
        function, this_handler->handler_));
}

template <typename Function, typename Dispatcher, typename Handler>
inline void asio_handler_invoke(const Function& function,
    post_handler<Dispatcher, Handler>* this_handler)
{
  this_handler->dispatcher_.post(
      boost::asio::detail::rewrapped_handler<Function, Handler>(
        function, this_handler->handler_));
}

/// @brief Factory function used to create handlers that post through the
///        dispatcher.
template <typename Dispatcher, typename Handler>
post_handler<Dispatcher, Handler>
wrap_post(Dispatcher dispatcher, Handler handler)
{
  return post_handler<Dispatcher, Handler>(dispatcher, handler);
}

/// @brief Convenience factory function used to wrap handlers created from
///        strand.wrap.
template <typename Dispatcher, typename Handler>
post_handler<Dispatcher, 
             boost::asio::detail::wrapped_handler<Dispatcher, Handler> >
wrap_post(boost::asio::detail::wrapped_handler<Dispatcher, Handler> handler)
{
  return wrap_post(handler.dispatcher_, handler);
}

boost::asio::io_service io_service;
boost::asio::strand strand(io_service);
boost::asio::deadline_timer timer(io_service);

void a() { std::cout << "a" << std::endl; }
void b() { std::cout << "b" << std::endl; }
void c() { std::cout << "c" << std::endl; }
void d() { std::cout << "d" << std::endl; }
void noop() {}

void my_great_function()
{
  std::cout << "++my_great_function++" << std::endl;
  // Standard dispatch.
  strand.dispatch(&a);

  // Direct wrapping.
  wrap_post(strand, &b)();

  // Convenience wrapping.
  wrap_post(strand.wrap(&c))();

  // ADL hooks.
  timer.async_wait(wrap_post(strand.wrap(boost::bind(&d))));
  timer.cancel();
  std::cout << "--my_great_function--" << std::endl;
}

int main()
{
  // Execute my_great_function not within a strand.  The noop
  // is used to force handler invocation within strand.
  io_service.post(&my_great_function);
  strand.post(&noop);
  io_service.run();
  io_service.reset();

  // Execute my_great_function within a strand.
  std::cout << std::endl;
  io_service.post(strand.wrap(&my_great_function));
  strand.post(&noop);
  io_service.run();
}

产生以下输出:

++my_great_function++
--my_great_function--
a
b
c
d

++my_great_function++
a
--my_great_function--
b
c
d

A slightly easier solution that depends on implementation details, is to adapt detail::wrapped_handler's Dispatcher type argument. This approach allows for wrapped_handlers with adapted Dispatcher types to be transparently used within the rest of Boost.Asio.

/// @brief Class used to adapter the wrapped_handler's Dispatcher type
///        requirement to post handlers instead of dispatching handlers.
template <typename Dispatcher>
struct post_adapter
{
  post_adapter(Dispatcher& dispatcher)
    : dispatcher_(dispatcher)
  {}

  template <typename Handler>
  void dispatch(const Handler& handler)
  {
    dispatcher_.post(handler);
  }

  Dispatcher dispatcher_;
};

/// @brief Factory function used to create handlers that post through an
///        adapted dispatcher.
template <typename Dispatcher, typename Handler>
boost::asio::detail::wrapped_handler<post_adapter<Dispatcher>, Handler>
wrap_post(Dispatcher& dispatcher, Handler handler)
{
  typedef post_adapter<Dispatcher> adapter_type;
  return boost::asio::detail::wrapped_handler<
    adapter_type, Handler>(adapter_type(dispatcher), handler);
}

/// @brief Convenience factory function used to wrap handlers created from
///        strand.wrap.
template <typename Dispatcher, typename Handler>
boost::asio::detail::wrapped_handler<
  post_adapter<Dispatcher>, 
  boost::asio::detail::wrapped_handler<Dispatcher, Handler> >
wrap_post(boost::asio::detail::wrapped_handler<Dispatcher, Handler> handler)
{
  return wrap_post(handler.dispatcher_, handler);
}

这两种 wrap_post 解决方案都可能会引入一定程度的复杂性,与定义的 order of handler invocations 有关。 .

关于c++ - 为什么没有 strand::wrap() 等同于 strand::post()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16240716/

有关c++ - 为什么没有 strand::wrap() 等同于 strand::post()?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  6. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  7. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  8. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  9. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou

  10. ruby-on-rails - rails : How to make a form post to another controller action - 2

    我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak

随机推荐