执行时使用 boost::asio::deadline_timer 时出错

Error using boost::asio::deadline_timer while execution

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

          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)

您没有显示互斥体 - 所以我们无法回答。

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

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

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

最小固定版本

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

Live On Coliru

#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

下运行干净