So I have code like:
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();
}
It gives me error:
Error 1 error C2248: boost::noncopyable_::noncopyable::noncopyable: "boost::noncopyable_::noncopyable" boost\asio\basic_io_object.hpp 93
开发者_如何学Python
How to make it possible to run my request_response_loop function in another thread that one I use for socket accepting?
To expand on Ben's answer, boost::shared_ptr<>
is the usual mechanism here:
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;
}
}
}
Next time show the entire error message.
Your problem is that your thread procedure wants a reference to the socket, but the socket is a local variable. The acceptor_loop
function doesn't wait, so it will destroy the socket as soon as it goes out of scope.
You need to use dynamic or static lifetime, never automatic, for variables passed between threads.
精彩评论