如何使用 c++ 11 使函数在所需的周期执行

2023-12-03

我想使用c++ 11来实现类似windows API的功能SetTimer,就像“每2秒做某事”


假设你想让这个函数每 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 c++ 11 使函数在所需的周期执行 的相关文章

随机推荐