有没有一种方法可以检查堆叠的协同程序是否在给定链的上下文中

Is there a way to check whether a stackful coroutine is in the context of a given strand?

本文关键字:是否 程序 上下文 一种 方法 检查 有没有      更新时间:2023-10-16

给定一个yield_context对象y和一个链s,是否有方法检查y是否代表s上下文中的协程?

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

#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也不会暴露协程的执行器上下文。

相关文章: