c++ - 奇怪的多线程问题

标签 c++ multithreading cpp-netlib

我有一个构造函数可以创建服务器的两个线程(我使用的是 cpp-netlib 库)。我得到的奇怪问题是,即使我没有在构造函数中调用 servlet1.join() 和 servlet2.join(),由于某种原因构造函数等待两个线程结束。即使这些线程永远不会结束。但是,如果我将相同的代码放在 main() 中,除非我调用 join(),否则它不会等待这两个线程。看看版本 A 和 B。

http_server* serv;

A-

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;
}

B-

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;
}

最佳答案

你有一个无限循环,因为你在 Server() 构造函数中实例化了一个服务器

在 A-

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;
}

关于c++ - 奇怪的多线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15010937/

相关文章:

c++ - HtmlHelp() 关闭我的 MFC 应用程序

c++ - 套接字主机名查找超时 : how to implement it?

c++ - 所以我给自己弄了一个线程池任务管理器系统。我应该从现在开始只使用它来创建所有线程吗?

c++ - 如何在 Visual Studio 2010 中使用 cpp-netlib?

c++ - 将类添加到 vector 不起作用

C++ CRTP(模板模式)问题

multithreading - 链式2 future -计算一个并返回另一个

c# - 如何等待 BackgroundWorker 取消?

c++ - CMake 找不到 cpp-netlib 库