c++ - 如何在多线程中安全地使用 boost deadline timer?

标签 c++ multithreading boost timer boost-asio

我像这段代码一样使用 boost 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代码。

没有任何互斥锁和同步,我可以在多线程中注册定时器吗?

另外,如果你发现我的代码有什么问题,请指教我。

感谢阅读。

最佳答案

截止时间计时器实例不是线程安全的。

单独的实例线程安全的。因此,要么使用单独的计时器,要么为访问添加同步。

文档链接:

关于c++ - 如何在多线程中安全地使用 boost deadline timer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22187019/

相关文章:

java - 如何杀死从第三方库导入的线程?

multithreading - TEventLog 组件线程安全吗?

c++ - 在哪里定义 _SILENCE_CXX17_ALLOCATOR_VOID_DEPRECATION_WARNING 或 _SILENCE_ALL_CXX17 DEPRECATION_WARNINGS 宏?

c++ - GCC 4.6.1 的链接问题

c++ - 组件系统的逆向转换

c++ - 尝试在 cpp 中打印 n 维数组

asp.net-mvc - ASP.Net MVC 中的线程安全

c++ - Boost.Asio IPv6 为什么绑定(bind)错误?

c++ - 遍历链表

使用枚举类的 C++11 标准符合位掩码