I was trying to implement the ActiveObject using boost::asio::io_service, but the result is not exactly as what I expected:
Below is my codes:
#include <boost/asio.hpp>
#include <chrono>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <memory>
#include <thread>
#include <string>
#include <functional>
#include <ctime>
#include <chrono>
#define SIZE 10
class ActiveObject
{
public:
ActiveObject()
{
executionThread_.reset( new std::thread( [&]{ service_.run(); } ) );
}
virtual ~ActiveObject()
{
// execute all unfinished work in case this object is leaving scope.
service_.poll();
service_.stop();
executionThread_->join();
std::cout << "active object thread exited" << std::endl;
}
void doSomething()
{
// post request the io_service to invoke someImpl method and return immediately
service_.post([=]{ someImpl();});
}
protected:
boost::asio::io_service service_;
private:
std::shared_ptr<std::thread> executionThread_;
void someImpl() {
std::chrono::milliseconds dura( 200 );
std::this_thread::sleep_for( dura );
std::cout << "poll thread id: " << std::this_thread::get_id() << std::endl;
}
};
int main()
{
std::cout << "main thread id: " << std::this_thread::get_id() << std::endl;
ActiveObject obj;
for(int i=0; i < SIZE; ++i) {
obj.doSomething(); // call is nonblocking
}
std::cout << "main thread exited " << std::endl;
return 0;
}
What I want is to run the boost::asio::io_service::run on the same thread, but it turns out not. From the log printed, the run() is also runned on the main thread. Below is the log printed:
main thread id: 140070853244800
main thread exited
poll thread id: 140070832256768
poll thread id: 140070853244800
poll thread id: 140070832256768
poll thread id: 140070853244800
poll thread id: 140070832256768
poll thread id: 140070853244800
poll thread id: 140070853244800
poll thread id: 140070832256768
poll thread id: 140070853244800
poll thread id: 140070832256768
active object thread exited
Any idea on this? Thanks