Using boost::asio::deadline_timer inside a thread

这一生的挚爱 提交于 2021-02-08 10:42:28

问题


I used boost::asio::deadline_timer to run a function. I have MosquitoInterface class as follow

class MosquitoInterface{

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

}

Inside my 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);
}

If I run io.run(); before while(run){ }, while(run){ } does not work. If I put io.run() after while(run){ }, the timer does not work. Since they are in main thread.

How to run boost::asio::deadline_timer inside a thread so that there is no blockage to the while loop.


回答1:


Just run the io_service on a separate thread. Be sure to post work (like async_wait) before that point, because otherwise the run() will return immediately.

Live On Coliru

Note the cleanup (removing all the unnecessary new and delete mess). Also, this is how you create a 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;
}


来源:https://stackoverflow.com/questions/40928020/using-boostasiodeadline-timer-inside-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!