在线程内使用boost :: asio :: deadline_timer [英] Using boost::asio::deadline_timer inside a thread
问题描述
我使用boost :: asio :: deadline_timer来运行一个函数.我有 MosquitoInterface
类,如下所示
I used boost::asio::deadline_timer to run a function.
I have MosquitoInterface
class as follow
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){}
之后,则计时器不起作用.因为它们在主线程中.
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.
如何在线程内运行boost :: asio :: deadline_timer,从而不会阻塞while循环.
How to run boost::asio::deadline_timer inside a thread so that there is no blockage to the while loop.
推荐答案
只需在单独的线程上运行io_service.确保在此之前发布工作(例如 async_wait
),否则run()将立即返回.
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.
注意清理(删除所有不必要的 new
和 delete
混乱).另外,这是您创建SSCCE的方式:
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;
}
这篇关于在线程内使用boost :: asio :: deadline_timer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!