我在C ++,Linux环境下编程。如何以异步方式和定期间隔在一定时间间隔后调用函数?我在http://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/tutorial/tuttimer2.html找到了Boost计时器。但是,它需要调用io.run()来调用回调,这反过来又让我回到原来的问题,即需要我处理调用该函数所用的时间。我需要的是类似C#System.Threading.Timer的东西,它会回调我在指定的时间段之后传递的函数。
我正在考虑为每个函数调用创建一个线程。但是,我有相当多的这种计时器回调。因此,我担心创建这样的线程会很昂贵,或者我有其他选择吗?
感谢。
答案 0 :(得分:5)
asio io_service
在自己的主题中运行,一旦你安排计时器事件,它会在适当的时候给你回电。
这是一个完整的例子:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
using namespace std;
class timed_class
{
public:
timed_class(boost::asio::io_service& io_service) : _timer(io_service)
{
// now schedule the first timer.
_timer.expires_from_now(boost::posix_time::milliseconds(100)); // runs every 100 ms
_timer.async_wait(boost::bind(&timed_class::handle_timeout, this, boost::asio::placeholders::error));
}
void handle_timeout(boost::system::error_code const& cError)
{
if (cError.value() == boost::asio::error::operation_aborted)
return;
if (cError && cError.value() != boost::asio::error::operation_aborted)
return; // throw an exception?
cout << "timer expired" << endl;
// Schedule the timer again...
_timer.expires_from_now(boost::posix_time::milliseconds(100)); // runs every 100 ms
_timer.async_wait(boost::bind(&timed_class::handle_timeout, this, boost::asio::placeholders::error));
}
private:
boost::asio::deadline_timer _timer;
};
int main(void)
{
boost::asio::io_service io_service;
timed_class t(io_service);
io_service.run();
return 0;
}
编辑:在一个单独的线程中发送,
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
而不是io_service.run();
,现在主线程将继续,一旦超时到期,io_service
将调用handle_timeout
答案 1 :(得分:1)
最简单解决方案的伪代码:
function doThis() {
// your code here
}
function threadHandler() {
sleep(SecondsUntilTime);
doThis();
}
function main () {
anotherthread = thread_create(threadHandler);
// more code here
join(anotherthread);
exit();
}
答案 2 :(得分:0)