Question

I have a constructor that creates two threads of a server (I am using the cpp-netlib library). The weird problem that I am getting is that even though I don't call servlet1.join() and servlet2.join() in the constructor, for some reason the constructor waits for the two threads to end. Even though these threads will never end. However, if I put the same code in main(), it will not wait for the two threads unless I call join(). Take a look at version A and 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;
}

main:

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;
}
Était-ce utile?

La solution

You have an infinite loop because you are instantiating a Server in the Server() constructor

in 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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top