I am using the boost library to implement a socket communication. In respect to my main application, a connection handler should be launched who deals with all incoming requests.
Therefore I have encapsulated the whole server handler into the class server. When the server object is created it should launch the server.
However this way the thread dies with the execution end of the constructor code. I guess I don't get how boost / posix threads work. I come from a Java background.
server::server(int port) {
try {
boost::asio::io_service io_service;
tcp_server server(io_service, port);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
} catch (std::exception&开发者_运维知识库 e) {
std::cerr << e.what() << std::endl;
}
You are constructing a local variable io_service
, which you pass to the worker function of your new thread. When the variable goes out of scope (constructor exits), io_service
is destroyed and can no longer be accessed.
However, your thread's worker function does not know this and presumably tries to access the remains of that object again. Ugliness ensues.
The error does not have to do with threads but is an instance of a common type of error called "returning the address of a local" (even though you are not actually returning it here, the mechanism is the same).
The solution would be to extend the lifetime of the io_service
object, either by taking manual control (new
/delete
) or by increasing it (e.g. making it a class member on server
instead of a local inside the constructor).
You also seem to have a problem with the server
variable, which is also a local and will be destroyed as soon as the constructor exists. Since you aren't actually using it at all this is not a problem with the code you posted, but anyway it's an indication that you are doing something suspicious.
Your io_service
needs to be primed with some io_service::work
to do, either explicitly or from your tcp_server
object. Otherwise io_service::run
() will return control immediately. Study the asio examples, this concept is important to understand.
The work class is used to inform the io_service when work starts and finishes. This ensures that the io_service object's run() function will not exit while work is underway, and that it does exit when there is no unfinished work remaining.
The work class is copy-constructible so that it may be used as a data member in a handler class. It is not assignable.
I suspect your code is a contrived example, it likely does not need a thread to run the io_service. The main thread will do just fine.
精彩评论