2016-12-02 11 views
0

私はboost :: asio :: deadline_timerを使って関数を実行しました。 私はio.run()を実行した場合、私のmain.cスレッド内でboost :: asio :: deadline_timerを使用する

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

内部

class MosquitoInterface{ 

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

} 

に従うようMosquitoInterfaceクラスを持っています。 while(run){ }の前には、while(run){ }は機能しません。 while(run){ }の後にio.run()と入力すると、タイマーが機能しません。 これはメインスレッドにあるためです。

スレッド内でboost :: asio :: deadline_timerを実行して、whileループの妨害がないようにする方法。

答えて

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; 
} 
関連する問題