对已删除的对象调用了deadline_timer回调
deadline_timer callback called on a deleted object
在流动的代码中,即使我从boost::enable_shared_from_this继承了net类,当net被删除时,OnTimer仍然会在一个无效对象上被调用一次。如何解决这个问题?提前谢谢。
boost::shared_ptr<boost::asio::io_service> service =
boost::make_shared<boost::asio::io_service>();
class net:public boost::enable_shared_from_this<net>
{
public:
net(boost::shared_ptr<boost::asio::io_service>& service);
void StartTimer();
void OnTimer(const boost::system::error_code& e);
~net();
private:
boost::asio::deadline_timer timer_;
int a;
};
net::net(boost::shared_ptr<boost::asio::io_service>& service)
:timer_(*service, boost::posix_time::milliseconds(1000))
{
}
net::~net()
{
timer_.cancel();
}
void net::StartTimer()
{
timer_.async_wait(boost::bind(&net::OnTimer,
shared_from_this(), boost::asio::placeholders::error));
}
void net::OnTimer(const boost::system::error_code& e)
{
a = 10;
timer_.async_wait(boost::bind(&net::OnTimer,
shared_from_this(), boost::asio::placeholders::error));
}
unsigned int WINAPI ThreadMain(void* arg)
{
boost::shared_ptr<net> ptr(new net(service));
ptr->StartTimer();
Sleep(5000);
boost::shared_ptr<net> invalid_ptr;
ptr = invalid_ptr;
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
boost::shared_ptr<boost::asio::io_service::work> io_service_work =
boost::make_shared<boost::asio::io_service::work>(*service);
boost::system::error_code ec;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadMain, NULL, 0, NULL);
if (hThread == NULL)
{
return -1;
}
boost::shared_ptr<boost::thread> thread_ =
boost::make_shared<boost::thread>(boost::bind(&boost::asio::io_service::run, service.get(), ec));
// in order to make sure OnTimer can be called at least once
Sleep(2000);
boost::shared_ptr<boost::asio::io_service::work> invalid_ptr;
io_service_work = invalid_ptr;
thread_->join();
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
return 0;
}
您正在使用boost::asio::占位符::error设置对OnTimer的回调,但忽略其错误代码。你真的应该得到并使用这个错误代码,否则你将访问已删除的net
实例的成员(变量a
和timer_
):
void net::OnTimer(const boost::system::error_code& e)
{
if( e == boost::asio::error::operation_aborted ) return; //Do nothing if timer is cancelled
if( e ) return; //Do nothing in case of error
a = 10;
timer_.async_wait(boost::bind(&net::OnTimer,
shared_from_this, boost::asio::placeholders::error));
}
相关文章:
- 是否需要在 Timer.5 boost::asio 教程中运行新线程?
- libevent是否允许在不同的线程中运行timer/io的回调
- QGraphicsView / Qgraphicsscene Timer事件不起作用
- 使用boost::asio::deadline_Timer实现通用Timer类时出现问题
- 创建 Timer 类时,我应该使用什么数据类型来保存值?(C/C++)
- C++ `Timer` class implementation
- 用c++编写Timer类
- Qt QLCDNumber Timer
- 在 c# 中是否有等效的 boost::timer::cpu_timer
- NachOS timer.cc 构造函数
- 在 c++ 中是否有像 timer 和 timertask 这样的东西,就像 java 一样
- c++计时器,相当于.NET System.Threading.timer
- 开始使用boost-cpu_timer时,错误:“boost::timer::cpu_timer”尚未声明
- 如何从boost::timer::cpu_timer获取以秒为单位的运行时间
- 如何为一些类(如timer类)编写单元测试
- 如何在c++中创建Timer任务
- Boost Timer 24小时格式
- 如何重启boost::timer::cpu_timer
- 在Timer ISR内使用FreeRTOS中的全局值
- Linux c++ timer周期性回调