【问题标题】:Using boost::asio::deadline_timer inside a thread在线程中使用 boost::asio::deadline_timer
【发布时间】:2016-12-02 08:47:10
【问题描述】:

我使用 boost::asio::deadline_timer 来运行一个函数。 我有MosquitoInterface 类如下

class MosquitoInterface{

   MosquitoInterface(deadline_timer &timer) : t(timer){}

}

在我的main.c里面

int main(int argc, char** argv )
{    

     io_service io;
     deadline_timer t(io);
     MosquitoInterface *m = new MosquitoInterface(t);


     io.run();

     d = new Detectdirection();      
     while(run)
     {   

        int ret =  d->Tracking();
        if(ret < 0)
           cout << "Pattern is not found" << endl ;
     }

     if(d!=NULL)    
        delete d;
     if(m!=NULL)
        delete m;
     cout << "Process Exit" << endl;
     exit(1);
}

如果我运行io.run();在while(run){ }while(run){ } 之前不起作用。 如果我将io.run() 放在while(run){ } 之后,则计时器不起作用。 因为它们在主线程中。

如何在线程内运行 boost::asio::deadline_timer 以便不会阻塞 while 循环。

【问题讨论】:

    标签: c++ multithreading boost boost-asio


    【解决方案1】:

    只需在单独的线程上运行 io_service。请务必在此之前发布工作(如 async_wait),否则 run() 将立即返回。

    Live On Coliru

    注意清理(删除所有不必要的newdelete 混乱)。另外,this 是您创建 SSCCE 的方式:

    #include <boost/asio.hpp>
    #include <thread>
    #include <iostream>
    #include <atomic>
    
    static std::atomic_bool s_runflag(true);
    
    struct Detectdirection {
        int Tracking() const { return rand()%10 - 1; }
    };
    
    struct MosquitoInterface{
       MosquitoInterface(boost::asio::deadline_timer &timer) : t(timer) {
           t.async_wait([](boost::system::error_code ec) { if (!ec) s_runflag = false; });
       }
       boost::asio::deadline_timer& t;
    };
    
    int main() {
        boost::asio::io_service io;
        boost::asio::deadline_timer t(io, boost::posix_time::seconds(3));
    
        MosquitoInterface m(t);
        std::thread th([&]{ io.run(); });
    
        Detectdirection d;
        while (s_runflag) {
            if (d.Tracking()<0) {
                std::cout << "Pattern is not found" << std::endl;
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
    
        th.join();
        std::cout << "Process Exit" << std::endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多