我有一个创建服务器的两个线程的构造函数(我正在使用 cpp-netlib 库)。我得到的奇怪问题是,即使我没有在构造函数中调用 servlet1.join() 和 servlet2.join(),由于某种原因,构造函数会等待两个线程结束。即使这些线程永远不会结束。但是,如果我将相同的代码放在 main() 中,它不会等待两个线程,除非我调用 join()。看看版本 A 和 B。
http_server* 服务;
一个-
Server()
{
boost::network::utils::thread_pool thread_pool(2);
Server handler();
serv = new http_server(0.0.0, 800, handler, thread_pool);
boost::thread servlet1(boost::bind(&http_server::run, serv));
boost::thread servlet2(boost::bind(&http_server::run, serv));
serv->run();
std::cout << "This never prints" << std::endl;
}
~Server()
{
serv->stop(); //this kills all threads and stops server gracefully
delete serv;
}
主要的:
int main()
{
std::cout << "hi" << std::endl; //this prints
Server* test = new Server();
std::cout << "hi" << std::endl; //this never prints
delete test;
}
乙-
int main()
{
boost::network::utils::thread_pool thread_pool(2);
Server handler();
serv = new http_server(0.0.0, 800, handler, thread_pool);
boost::thread servlet1(boost::bind(&http_server::run, serv));
boost::thread servlet2(boost::bind(&http_server::run, serv));
serv->run();
std::cout << "This always prints" << std::endl;
}