2

我试图调用boost::asio::spawn相同的两次boost::asio::io_context::strand,每次都传递一个协程,我希望这两个协程一个接一个地执行,但它们是并行执行的。这是说明这一点的代码:

boost::asio::io_context ioc;
boost::asio::io_context::strand strand{ioc};
boost::asio::spawn(strand, [&](boost::asio::yield_context yield)
                   {
                       cout << "1\n";
                       ioc.post(yield);
                       cout << "2\n";
                       ioc.post(yield);
                       cout << "3\n";
                   });

boost::asio::spawn(strand, [&](boost::asio::yield_context yield)
                   {
                       cout << "10\n";
                       ioc.post(yield);
                       cout << "20\n";
                       ioc.post(yield);
                       cout << "30\n";
                   });
ioc.run();

这输出:

1
10
2
20
3
30

当我期待:

1
2
3
10
20
30

在实际代码中,第一个协程设置一个套接字(通过解析/连接/握手的动作),第二个协程进行发送/接收。我的意图是将第二个协程“附加”到链中,并且只有在第一个协程完成时才开始执行。

我怎样才能达到这个效果?

编辑:更多上下文。第一个协程在构造函数中,第二个在成员函数中。如果我想允许用户写

Foo foo;
foo.bar();

如何确保构造函数中的协程在 bar() 中的协程开始之前完成?

4

1 回答 1

2

strands 只保证它们的函数不会同时在多个线程上执行。这使您无需使用锁。

它们不会使单独的函数按顺序执行。如果您想要顺序执行,只需在第一个函数的末尾调用您的第二个函数:

boost::asio::io_context ioc;
boost::asio::io_context::strand strand{ioc};
auto main = [&](boost::asio::yield_context yield)
                   {
                       cout << "10\n";
                       ioc.post(yield);
                       cout << "20\n";
                       ioc.post(yield);
                       cout << "30\n";
                   };
boost::asio::spawn(strand, [&](boost::asio::yield_context yield)
                   {
                       cout << "1\n";
                       ioc.post(yield);
                       cout << "2\n";
                       ioc.post(yield);
                       cout << "3\n";
                       main();
                   });

如果你不能从第一个函数调用第二个函数,我已经使用过几次的技术是有一个要执行的函数队列,因为一切都在一个链中,无需担心锁定:

bool executing = false;
struct ExecuteLock
{
  ExecuteLock()
  {
    if ( !executing )
    {
      executing = true;
      locked = true;
    }
    else
    {
      locked = false;
    }
  }

  ~ExecuteLock()
  {
    if ( locked )
    {
      executing = false;
    }
  }

  bool locked;
};

typedef QueueFunction std::function<void(boost::asio::yield_context yield);

std::queue< QueueFunction > executeQueue;

void run( QueueFunction f )
{
  boost::asio::spawn( strand, [=](boost::asio::yield_context yield)
  {
    ExecuteLock lock;
    if (!lock.locked)
    {
      executeQueue.push( f );
      return;
    }
    f();
    while ( !executeQueue.empty() )
    {
      executeQueue.front()();
      executeQueue.pop();
    }
  } );
}

然后,您可以在run()每次要执行某些操作时调用。

于 2018-09-09T16:41:57.963 回答