假设你想让这个函数每 2 秒执行一次
void foo() {
cout << "Hello from foo()!" << endl;
}
您可以提供一个简单的timed_execution
使用各种 c++11 机制的类
struct timed_execution {
typedef void (*func_type)(void);
timed_execution(func_type func, const std::chrono::milliseconds period)
: func_(func)
, period_(period)
, thread_(std::bind(&timed_execution::threadFunc,this))
{
}
private:
void threadFunc() {
while(true) {
std::this_thread::sleep_for(period_);
func_();
}
}
func_type func_;
const std::chrono::milliseconds period_;
std::thread thread_;
};
要在一定时间内异步运行该函数,您只需创建此类的一个实例:
int main() {
timed_execution t(foo,std::chrono::milliseconds(2000));
std::this_thread::sleep_for(std::chrono::seconds(60));
return 0;
}
See a 现场样本在这里 please.
利用模板/可变参数模板来提供实际要执行的函数的参数和返回类型,似乎是改进timed_execution
上课并去参加timer
类如下:
template<typename CALLBACK_T>
struct timer {
template<typename D>
timer(CALLBACK_T func, const D& period)
: func_(func)
, period_(std::chrono::duration_cast<std::chrono::milliseconds>( period ))
, thread_(std::bind(&timer::threadFunc,this))
{
}
private:
void threadFunc() {
while(true) {
std::this_thread::sleep_for(period_);
func_();
}
}
CALLBACK_T func_;
const std::chrono::milliseconds period_;
std::thread thread_;
};
并且有一个单独的make_timer()
函数来实例化它
template<typename CALLBACK_T , typename D>
timer<typename std::decay<CALLBACK_T>::type> make_timer( CALLBACK_T&& callback , D&& duration )
{
return { std::forward<CALLBACK_T>( callback ) , std::forward<D>( duration ) };
}
int main() {
auto timer = make_timer(foo,std::chrono::seconds(1));
auto other = make_timer( [](){ std::cout << "Hello from lambda!\n"; } , std::chrono::seconds{ 1 } );
std::this_thread::sleep_for(std::chrono::seconds(60));
return 0;
}