Io_service is executed inside the thread
Why, in this simple class, if I use io.run () directly , the function will be called otherwise, if a run needs to be done on another thread, the print will not be called?
#include <iostream>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
using namespace std;
class test
{
public:
test()
{
io.post(boost::bind(&test::print, this));
//io.run();
t = boost::thread(boost::bind(&boost::asio::io_service::run, &io));
}
void print()
{
cout << "test..." << endl;
}
private:
boost::thread t;
boost::asio::io_service io;
};
int main()
{
test();
return 0;
}
source to share
The thread object is destroyed before being allowed io_service
to run completely. The thread
destructor documentation says:
[...] the programmer must ensure that the destructor never gets executed while the thread is still compatible.
If BOOST_THREAD_PROVIDES_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE
defined, the program will be aborted as the thread's destructor will call std::terminate()
.
If io_service
must run to completion, consider concatenating the stream inside a Test
destructor. Here is a complete example that shows synchronization at the end of the flow:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
class test
{
public:
test()
{
io.post(boost::bind(&test::print, this));
t = boost::thread(boost::bind(&boost::asio::io_service::run, &io));
}
~test()
{
if (t.joinable())
t.join();
}
void print()
{
std::cout << "test..." << std::endl;
}
private:
boost::thread t;
boost::asio::io_service io;
};
int main()
{
test();
return 0;
}
Output:
test...
source to share