【发布时间】:2014-04-03 01:23:16
【问题描述】:
我试图使用 boost::asio::io_service 实现ActiveObject,但结果并不完全符合我的预期:
以下是我的代码:
#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;
}
我想要的是在同一个线程上运行 boost::asio::io_service::run,但事实证明不是。从打印的日志来看,run() 也在主线程上运行。以下是打印的日志:
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
对此有任何想法吗?谢谢
【问题讨论】:
-
This 回答可能会提供有关如何在活动对象模式中实现某些元素的想法。
标签: c++ boost boost-asio