我想在 C++ 中实现一些系统,以便我可以调用一个函数并要求在 X 毫秒内调用另一个函数。像这样的:
callfunctiontimed(25, funcName);
25 是调用函数之前的毫秒数。
我想知道这是否需要多线程,然后使用一些延迟功能?除了使用函数指针之外,这样的功能如何工作?
最佳答案
对于可移植解决方案,您可以使用 boost::asio。下面是我前段时间写的一个demo。 你可以改变
t.expires_from_now(boost::posix_time::seconds(1));
为了适合你需要在 200 毫秒后调用函数。
t.expires_from_now(boost::posix_time::milliseconds(200));
下面是一个完整的工作示例。它在重复调用,但我认为只需稍微更改一下就可以轻松调用一次。
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::asio;
using namespace std;
class Deadline
{
public:
Deadline(deadline_timer &timer) : t(timer) {
wait();
}
void timeout(const boost::system::error_code &e) {
if (e)
return;
cout << "tick" << endl;
wait();
}
void cancel() {
t.cancel();
}
private:
void wait() {
t.expires_from_now(boost::posix_time::seconds(1)); //repeat rate here
t.async_wait(boost::bind(&Deadline::timeout, this, boost::asio::placeholders::error));
}
deadline_timer &t;
};
class CancelDeadline {
public:
CancelDeadline(Deadline &d) :dl(d) { }
void operator()() {
string cancel;
cin >> cancel;
dl.cancel();
return;
}
private:
Deadline &dl;
};
int main()
{
io_service io;
deadline_timer t(io);
Deadline d(t);
CancelDeadline cd(d);
boost::thread thr1(cd);
io.run();
return 0;
}
//result:
//it keeps printing tick every second until you enter cancel and enter in the console
tick
tick
tick
关于c++实现定时回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12904098/