2016-12-02 7 views
0

나는 boost :: asio :: deadline_timer를 사용하여 함수를 실행했습니다. 내부스레드 내에서 boost :: asio :: deadline_timer 사용

class MosquitoInterface{ 

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

} 

를 따를 때 나는 MosquitoInterface 클래스가 내 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){ }이 작동하지 않습니다. while(run){ } 뒤에 io.run()을 입력하면 타이머가 작동하지 않습니다. 메인 스레드에 있기 때문에.

while 루프에 방해가되지 않도록 스레드 내에서 boost :: asio :: deadline_timer를 실행하는 방법.

답변

1

io_service를 별도의 스레드에서 실행하십시오. 이 시점 이전에 작업 (예 : async_wait)을 게시해야합니다. 그렇지 않으면 run()이 즉시 반환되기 때문입니다.

Live On Coliru

주 (모든 불필요한 newdelete 혼란을 제거) 정리. 또한 은 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; 
}