gpt4 book ai didi

c++ - io_service 在销毁时挂起

转载 作者:行者123 更新时间:2023-11-30 03:49:25 25 4
gpt4 key购买 nike

我使用 boost::asio::io_service 来处理 Foo 中的工作。现在它工作正常,直到我退出 ~Foo 并卡在 io_service 析构函数(在 service_registry 的析构函数中)的某个地方。我做错了什么吗?

struct Foo {
Foo();
~Foo();
void bar();
boost::asio::io_service _ioService;
unique_ptr<boost::asio::io_service::work> _ioWork;
thread _thread;
};

Foo::Foo() :
_ioWork( new boost::asio::io_service::work(_ioService) ),
_thread([&]() {
_ioService.run();
}) {
}

Foo::~Foo() {
_ioWork.release();
_ioService.stop();
_thread.join();
// works great till here
}

void
Foo::bar() {
auto writer = []()
{
// Some magic code
};

_ioService.post( writer );
}

我有点奇怪,当我没有在 _ioService 上调用 stop 时,为什么 _thread 不会加入。

最佳答案

不要调用_ioWork.release()(或者在调用release之后,删除你得到的指针)。

以下是文档中关于release 的内容:

Releases the ownership of the managed object if any. get() returns nullptr after the call.

在您的代码中,您的 _ioWork 对象被泄露;这可能是导致您的 ioService 挂起的原因。

关于c++ - io_service 在销毁时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32566468/

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