为什么boost不会在这种情况下创建一个线程(C2248)以及如何创建它?

时间:2011-04-13 23:50:47

标签: c++ multithreading boost boost-asio boost-thread

所以我的代码如下:

using namespace boost::asio::ip;
using namespace std;

void request_response_loop(boost::asio::ip::tcp::socket& socket)
{
    http_request request(socket);
    http_response response;
    response.body = "<head></head><body><h1>It Rocks!</h1></body>";
    response.send(socket);
    socket.close();
    cout << "connection resolved." << endl;
}


void acceptor_loop(){
    boost::asio::io_service io_service;
    int m_nPort = 12345;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), m_nPort));
    cout << "Waiting for connection..." << endl;
    while(true)
    {
        try
        {
            tcp::socket socket(io_service);
            acceptor.accept(socket);
            cout << "connection accepted." << endl;
            boost::thread workerThread2(request_response_loop, socket); // here it does not compile because of C2248
        }
        catch(exception &e)
        {
            cerr << e.what() << endl; //"The parameter is incorrect" exception
        }
    }
}
int main()
{ 
    boost::thread workerThread(acceptor_loop);
    cin.get();
}

它给了我错误:

Error   1   error C2248: boost::noncopyable_::noncopyable::noncopyable: "boost::noncopyable_::noncopyable"  boost\asio\basic_io_object.hpp  93  

如何在我用于套接字接受的另一个线程中运行我的request_response_loop函数?

2 个答案:

答案 0 :(得分:3)

为了扩展Ben的答案,boost::shared_ptr<>是通常的机制:

void request_response_loop(boost::shared_ptr<tcp::socket> socket)
{
    http_request request(*socket);
    http_response response;
    response.body = "<head></head><body><h1>It Rocks!</h1></body>";
    response.send(*socket);
    socket->close();
    cout << "connection resolved." << endl;
}

void acceptor_loop()
{
    boost::asio::io_service io_service;
    int m_nPort = 12345;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), m_nPort));
    cout << "Waiting for connection..." << endl;
    while(true)
    {
        try
        {
            boost::shared_ptr<tcp::socket> socket =
                boost::make_shared<tcp::socket>(boost::ref(io_service));
            acceptor.accept(*socket);
            cout << "connection accepted." << endl;
            boost::thread workerThread2(request_response_loop, socket);
        }
        catch(exception &e)
        {
            cerr << e.what() << endl;
        }
    }
}

答案 1 :(得分:2)

下次显示整个错误消息。

您的问题是您的线程过程需要引用套接字,但套接字是一个局部变量。 acceptor_loop函数不会等待,所以它会在超出范围时立即销毁套接字。

对于在线程之间传递的变量,您需要使用动态或静态生命周期,而不是自动生成。