我有一个关于 boost asio 计时器和安全线程与它们一起工作的问题。比方说,我有以下类(class):
CTest.h:
class CTest
{
boost::asio::io_service io;
boost::asio::deadline_timer timer;
void Check();
CTest ();
~CTest ();
};
和 CTest.cpp:
CTest::CTest():
timer (io, boost::posix_time::seconds(0))
{
timer.async_wait(boost::bind(&CTest::Check, this));
boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
}
void CTest::Check()
{
//some work
m_timer.expires_from_now(boost::posix_time::seconds(10));
m_timer.async_wait(boost::bind(&CTest::Check, this));
}
CTest::~CTest()
{
io.stop();
}
那么,问题是如何完成Check thread safe?我的意思是,这个 Check 函数可以在析构函数之后调用,我们就崩溃了。
最佳答案
使用 io_service::stop() 很少是您想做的。
几点:
- 保留线程对象,并调用 thread.join() 以确保它已完成。
- 不要调用 io.stop(),调用 m_timer.cancel(),然后调用 m_thread.join() 进行清理。
- 考虑使用 shared_ptr 和 weak_ptr 来更干净地管理对象生命周期(即:将 weak_ptr 实例绑定(bind)到您的 async_wait 回调中,而不是裸露的
this
。在回调函数中,将 weak_ptr 转换为 shared_ptr 并如果有效,则调用该方法。 - m_timer 将在多个线程中使用,您需要使用互斥锁来管理访问。
就几点。不会为您重写代码。
关于c++ - boost::asio 计时器的线程安全工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15610872/