boost :: asio :: io_service.post()背景线程内存使用情况

boost::asio::io_service.post() background thread memory usage

本文关键字:线程 背景 内存 用情 情况 io asio service post boost      更新时间:2023-10-16

我想在背景线程中运行boost::asio::io_service.run()。因此,当我需要它时,post()func in。

这是主要功能:

int main(int /*argc*/, char** /*argv*/)
{
    std::string message = "hello";
    logg = new logger_client(filename,ip,13666);
    logg->start();
    while (true)
        logg->add_string(message);
    return 0;
}

和一些来自logger_client的相关函数:

std::auto_ptr<boost::asio::io_service::work> work;
logger_client::logger_client(std::string& filename,std::string& ip, uint16_t port) : work(new boost::asio::io_service::work(io_service))
{
}
void logger_client::start()
{
    ios_thread = new boost::thread(boost::bind(&io_service.run,&io_service));
}
void print_nothing()
{
    printf("%sn","lie");
}
void logger_client::add_string(std::string& message)
{
    io_service.post(boost::bind(print_nothing));
    //io_service.post(strand->wrap(boost::bind(&logger_client::add_string_imp,this,message)));
    //io_service.run();
}

当我运行此操作时,我的程序会少于2GB。如果我删除无尽的工作并对此进行更改:

void logger_client::add_string(std::string& message)
{
    io_service.post(boost::bind(print_nothing));
    //io_service.post(strand->wrap(boost::bind(&logger_client::add_string_imp,this,message)));
    io_service.run();
}

程序效果很好。但是我不想在此(主)线程上调用异步操作。我在做什么错?

更新

我在(true)循环中添加了睡眠(1秒),并且内存不再生长。但这不是解决方案。因为如果我在post()之后调用run()(即使用主线程进行处理手柄),甚至在(true)loops内存不会增长的情况下添加五个线程。那么,为什么主线程比新创建的好得多呢?我还尝试了用于IO_Service :: Run的线程池 -

io_service.run Will exit 除非有未决操作。

因此,您的ios_thread将立即退出。

解决方案是使用io_service :: Work。

此外,像这样的无尽循环垃圾邮件

 while (true)
        logg->add_string(message);

不是一个好主意,也许添加一些睡眠(),以使其放慢一点并保持控制。