如何在多个线程中安全地使用提升截止时间计时器
How to safely use boost deadline timer in multiple threads?
我使用像下面的代码这样的提升deadline_timer:
boost::asio::io_service g_io;
#define DEL(x) {delete x; x = NULL;}
void thr1()
{
for(;;)
{
...
boost::asio::deadline_timer *t1 = new boost::asio::deadline_timer(g_io, boost::posix_time::seconds(60));
t1->async_wait(boost::bind(&callback, boost::asio::placeholders::error, t1));
...
}
}
void thr2()
{
for(;;)
{
....
boost::asio::deadline_timer *t2 = new boost::asio::deadline_timer(g_io, boost::posix_time::seconds(60));
t2->async_wait(boost::bind(&callback, boost::asio::placeholders::error, t2));
....
}
}
void thr3()
{
for(;;)
{
....
boost::asio::deadline_timer *t3 = new boost::asio::deadline_timer(g_io, boost::posix_time::seconds(60));
t3->async_wait(boost::bind(&callback, boost::asio::placeholders::error, t3));
....
}
}
void thr4()
{
for(;;)
{
....
boost::asio::deadline_timer *t4 = new boost::asio::deadline_timer(g_io, boost::posix_time::seconds(60));
t4->async_wait(boost::bind(&callback, boost::asio::placeholders::error, t4));
....
}
}
void io_work()
{
boost::asio::io_service::work work(g_io);
g_io.run();
}
int main()
{
boost::thread thread1(thr1);
boost::thread thread2(thr2);
boost::thread thread3(thr3);
boost::thread thread4(thr4);
boost::thread service_thread(io_work);
thread1.join();
thread2.join();
thread3.join();
thread4.join();
service_thread.join();
return 0;
}
void callback(const boost::system::error_code& e, boost::asio::deadline_timer *timer)
{
if(e)
{
std::cout << "cancel" << std::endl;
}
else
{
std::cout << " time out occurred" << std::endl;
if(timer->expires_at() <= boost::asio::deadline_timer::traits_type::now())
{
if(timer) DEL(timer);
return;
}
timer->expires_at(timer->expires_at()+boost::posix_time::seconds(1));
timer->async_wait(boost::bind(callback, boost::asio::placeholders::error, timer));
}
}
计时器运行良好。但是,当出现奇怪的错误时,我总是首先怀疑我的asio代码,因为我找不到与我编写的类似的asio代码。
在没有任何互斥锁或同步的情况下,我可以在多线程中注册计时器吗?
另外,如果您在mycode中发现任何问题,请告诉我。
感谢您的阅读。
截止时间计时器实例不是线程安全的。
单独的实例是线程安全的。因此,要么使用单独的计时器,要么向访问添加同步。
文档链接:
- http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/deadline_timer.html#boost_asio.reference.deadline_timer.thread_safety
您应该
注意到,您的callback
函数将始终在被调用io_service.run()
线程中调用,这在您的情况下service_thread
。因此,您可以在不同步的情况下访问两个线程上的计时器对象,这在没有同步的情况下是不安全的。
但是,确切的情况取决于您的完整代码(...
部分中的内容)。如果您完全按照示例中的方式执行此操作(仅在第一个线程中创建和启动计时器(保证在回调之前发生)并且仅在io_service线程中向后访问它,它应该是安全的。
相关文章:
- Linux的Cpp上的计时器
- 提升 ASIO 无法识别计时器对象
- 使计时器在C++进程中的特定时间关闭,以便同步两个进程
- C :从一定的时间戳启动计时器,然后将其增加
- 如果STD :: COUT发表评论,则计时器需要更长的时间才能达到10.f秒
- 在一段时间内进行计时器
- 如何在多个线程中安全地使用提升截止时间计时器
- 在运行时间内用户输入任何内容时,如何停止计时器
- 唤醒asio截止时间计时器
- 如何在C++中使用计时器在给定时间内强制输入
- 最适合正确测量缓存访问时间的计时器
- 制作一个计时器,在以毫秒为单位的一定时间后执行某个函数
- C++计时器(等待一段时间)
- 如何在没有计时器的情况下确定经过了多少时间
- 通过引用传递与通过指针传递:Boost线程和截止时间计时器
- 如何在c++中使用boost实现与系统时间无关的计时器回调
- 如何获得比Windows XP上的计时器滴答(15毫秒)更高精度的时间
- 你如何嘲笑助推计时器的时间
- 用户计时器在第一次使用后出错,无论我等待多长时间都会返回零
- 使用Boost基本截止时间计时器来调用类方法