boost::asio::io_service.post() background thread memory usage
我想在后台线程中运行
这是主要功能:
1 2 3 4 5 6 7 8 9 10 11 12 | 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的一些相关功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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\ ","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。如果我删除了无休止的工作并更改为:
1 2 3 4 5 6 | 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。
此外,像这样的无休止循环垃圾邮件
1 2 | while (true) logg->add_string(message); |
不是一个好主意,也许添加一些sleep(),以使其放慢速度并使其处于受控状态。