【发布时间】:2018-10-09 03:02:04
【问题描述】:
我想让程序等到它完成所有正在运行的线程,这与ioService.stop(); 不同,后者无需等待即可停止ioService。我尝试了以下代码,它工作正常,但停止 ioService 而不等待线程完成。
#include <iostream>
#include <boost/asio/io_service.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
void myTask (std::string &str);
int main(int argc, char **argv){
uint16_t total_threads = 4;
/*
* Create an asio::io_service and a thread_group
*/
boost::asio::io_service ioService;
boost::thread_group threadpool;
/*
* This will start the ioService processing loop.
*/
boost::asio::io_service::work work(ioService);
/*
* This will add threads to the thread pool.
*/
for (std::size_t i = 0; i < total_threads; ++i)
threadpool.create_thread(
boost::bind(&boost::asio::io_service::run, &ioService));
/*
* This will assign tasks to the thread pool.
*/
std::string str = "Hello world";
ioService.post(boost::bind(myTask, std::ref(str) ));
ioService.stop();
/*
* thread pool are finished with
* their assigned tasks and 'join' them.
*/
threadpool.join_all();
return 0;
}
void myTask (std::string &str){
std::cout << str << std::endl;
}
编译:-lboost_serialization -lboost_thread -lboost_system
【问题讨论】:
-
如果您甚至没有得到要编译的东西,停止服务不是您的问题,因此您可能应该重新考虑您的问题。另外,提取minimal reproducible example。
-
@UlrichEckhardt 怎么不是Minimal, Complete, and Verifiable example?我已经给出了每个人都可以运行并验证错误和其他详细信息的最少代码。
-
可以打包成一个文件吗?你能删除导致错误的行后面的行吗?
-
@UlrichEckhardt 我已经更新了我的问题。谢谢。
标签: c++ boost boost-asio boost-thread