gpt4 book ai didi

c++ - boost::asio::io_service.post() 后台线程内存使用

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

我想在后台线程中运行 boost::asio::io_service.run()。所以当我需要它时 post() func into.

这是主要功能:

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("%s\n","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();
}

程序运行良好。但我不想在此(主)线程上调用异步操作。我做错了什么?

更新

我在 while(true) 循环中添加了 sleep(1sec),内存不再增长。但这不是解决方案。因为如果我在 post() 之后调用 run() (即使用主线程处理句柄),甚至再添加五个带有 while(true) 循环的线程,内存就不会增长。那么为什么主线程比新创建的线程好这么多呢?我还尝试了 io_service::run 的线程池 - 没有帮助。

最佳答案

io_service.run 将退出,除非有待处理的操作。

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

解决方案是使用io_service::work .

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

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

这不是一个好主意,也许可以添加一些 sleep(),以减慢它的速度并使其处于受控状态。

关于c++ - boost::asio::io_service.post() 后台线程内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37966537/

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