执行时使用 boost::asio::d eadline_timer 时出错



我正在尝试使用以下代码实现一个基本的截止时间计时器:

class Example
{
Example(boost::asio::io_service& ios, config& cfg)
: ios_(ios), cfg_(cfg), tcp_client_(ios) {

state = new State();
boost::asio::deadline_timer t(ios, boost::posix_time::seconds(5));
t.async_wait(boost::bind(&bse_dummy_exchange::start_heartbeats,this,boost::asio::placeholders::error,boost::ref(t)));
}
~Example() = default;
void start_heartbeats(const boost::system::error_code& e,boost::asio::deadline_timer& t)
{
std::cout << "Hello, world!n";
t.expires_from_now(boost::posix_time::seconds(5));
t.async_wait(boost::bind(&bse_dummy_exchange::start_heartbeats,this,boost::asio::placeholders::error,boost::ref(t)));
}
}

编译正常,但是在执行时我收到此错误消息,我不明白,有人可以帮我吗:

Hello, world!
bse_dummy_exchange: ../nptl/pthread_mutex_lock.c:425: 
__pthread_mutex_lock_full: Assertion `INTERNAL_SYSCALL_ERRNO (e, __err) 
!= ESRCH || !robust' failed.
Aborted (core dumped)

您不显示互斥锁 - 所以我们无法回答。

也就是说,关于异步的所有事情都出错了,可能会出错:

  • 您有一个内存泄漏(state是拥有的指针成员,但您默认了析构函数? https://www.google.com/search?q=cppreference+rule+of+three&oq=cppreference+rule+of+three&aqs=chrome..69i57j69i64.2928j0j7&sourceid=chrome&ie=UTF-8(

  • 这是 UB:

    boost::asio::deadline_timer t(ios, boost::posix_time::seconds(5));
    t.async_wait(boost::bind(&bse_dummy_exchange::start_heartbeats,this,boost::asio::placeholders::error,boost::ref(t)));
    

    async_立即返回,但操作运行...井。。。异步。在您的情况下t是一个局部变量,在构造函数返回后立即超出范围。所以,这是行不通的。

  • start_heartbeats中完全相同的问题

(我是为了理解你的代码,假设Example实际上被命名为use_dummy_exchange(

至少,计时器的生存期需要超过async_wait的生存期。

最小固定版本

当然,不修复与互斥错误相关的任何内容 - 不包括在内:

住在科里鲁

#include <boost/asio.hpp>
#include <iostream>
struct config { };
struct TcpClient {
TcpClient(boost::asio::io_service& ios) : ios_(ios){}
private:
boost::asio::io_service& ios_;
};
struct Example {
struct State {};
std::unique_ptr<State> state;
Example(boost::asio::io_service& ios, config& cfg)
: state(std::unique_ptr<State>()),
ios_(ios),
cfg_(cfg),
tcp_client_(ios)
{
heartbeats();
}
void heartbeats(const boost::system::error_code& e = {}) {
std::cout << "Hello, world!" << std::endl;
if (!e) {
t.expires_from_now(boost::posix_time::seconds(5));
t.async_wait([this](auto ec) { heartbeats(ec); });
}
}
private:
boost::asio::io_service& ios_;
config cfg_;
TcpClient tcp_client_;
boost::asio::deadline_timer t{ios_};
};
int main() {
boost::asio::io_service ios;
config cfg;
Example ex(ios, cfg);
ios.run_for(std::chrono::seconds(12));
}

指纹

Hello, world!
Hello, world!
Hello, world!

它没有内存泄漏,并且在 UBSan/ASan 下运行干净

最新更新