gpt4 book ai didi

c++ - 刷新 boost::asio 中的所有异步处理程序

转载 作者:太空狗 更新时间:2023-10-29 20:17:53 26 4
gpt4 key购买 nike

我正在运行一些需要异步通信的测试,底层框架是Asio。有时,出于充分的理由,即使测试已被拆除,处理程序也会保留在处理循环中。但是随后,目标被删除后,它被调用。

测试类:

virtual void SetUp()
{
_client = new Client;
_server = new Server;

Service::run();
}

virtual void TearDown()
{
Service::stop();

delete _client;
delete _server;
}

服务类:

static void run()
{
_thread = new asio::thread(boost::bind(&asio::io_service::run, _service));
}

static void stop()
{
_service->stop();

_thread->join();
delete _thread;

_service->reset();
}

io_service::stop() 是非阻塞的,所以在我的例子中它变得毫无用处。如果我在函数末尾删除 io_service 对象,将不会调用处理程序,但我想要一个更好的解决方案来强制完成 before 对象是已删除。

注意:实际的处理循环是在第二个线程中完成的,但它是在一个 io_service::stop() 包装器中加入的,整个问题似乎与线程无关.

我正在使用 Asio(非 Boost)1.4.5,但可以考虑升级(以获得 io_service::stopped() 操作?)。

编辑:添加 io_service 包装器代码,因为根据评论它似乎是相关的。

最佳答案

在我看来,您需要稍微重新考虑一下您的设计。正如您所注意到的,io_service::stop 确实是异步的。它会导致对 io_service::run() 的任何调用尽快返回。在 ~io_service() 析构函数运行之前,不会使用 boost::asio::error::operation_aborted 调用任何未完成的处理程序。要管理对象生命周期,您应该使用 shared_ptr 作为 documentation建议:

The destruction sequence described above permits programs to simplify their resource management by using shared_ptr<>. Where an object's lifetime is tied to the lifetime of a connection (or some other sequence of asynchronous operations), a shared_ptr to the object would be bound into the handlers for all asynchronous operations associated with it. This works as follows:

  • When a single connection ends, all associated asynchronous operations complete. The corresponding handler objects are destroyed, and all shared_ptr references to the objects are destroyed.
  • To shut down the whole program, the io_service function stop() is called to terminate any run() calls as soon as possible. The io_service destructor defined above destroys all handlers, causing all shared_ptr references to all connection objects to be destroyed.

更具体地说,你有一个竞争条件

virtual void TearDown()
{
service->stop();

// ok, io_service is no longer running
// what if outstanding handlers use _client or _server ??

delete _client;
delete _server;

// now you have undefined behavior due to a dangling pointer
}

关于c++ - 刷新 boost::asio 中的所有异步处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5675768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com