有没有办法检查堆栈协程是否在给定链的上下文中?

时间:2014-10-26 05:35:50

标签: c++ boost boost-asio

鉴于yield_context对象y和一个s链,是否可以检查y是否代表s上下文中的协程不是吗?

1 个答案:

答案 0 :(得分:3)

给定yield_contextstrand对象,无法检测yield_context的执行程序上下文是否为特定strand。但是,在协程的执行中,可以通过调用strand::running_in_this_thread()来检测当前协同程序的执行程序上下文是否是特定的strand。这是一个微妙的区别,但这里有一个例子demonstrating的用法:

#include <cassert>
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>

int main()
{
  boost::asio::io_service io_service;
  boost::asio::io_service::strand strand1(io_service);
  boost::asio::io_service::strand strand2(io_service);
  boost::asio::io_service::strand strand3(strand1);

  boost::asio::spawn(strand1,
    [&](boost::asio::yield_context yield)
    {
      assert(strand1.running_in_this_thread());
      assert(!strand2.running_in_this_thread());
      assert(strand3.running_in_this_thread());

      // Access implementation details.
      auto strand4 = yield.handler_.dispatcher_;
      assert(strand4.running_in_this_thread());

      // No way to compare strands to one another.  Although strand1, strand3,
      // and strand4 use the same strand implementation, the strand objects
      // are neither identifiable nor comparable.
    });

  io_service.run();
}

无法检测yield_context对象的执行程序上下文是否是特定strand对象的原因是strand API既未提供执行标识也未提供比较的方法。在上面的示例中,虽然strand1strand3strand4引用相同的链实现,但推断它们使用相同实现的唯一方法是检查执行中的每个实现其中一条股的背景。此外,即使绞线具有可比性,yield_context支持的API也不会暴露协程的执行程序上下文。

相关问题