如何使用C ++ 11使函数在所需的时间执行 [英] How to make a function execute at the desired periods using c++ 11

查看:124
本文介绍了如何使用C ++ 11使函数在所需的时间执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用c ++ 11来实现类似于Windows API的功能

I want to using c++ 11 to implement a function like the windows API SetTimer,like that"do something every 2 second"

推荐答案

假设您希望每2秒执行一次此功能

Supposed you want to have this function being executed every 2 seconds

void foo() {
    cout << "Hello from foo()!" << endl;
}

您可以使用各种c ++ 11机制提供一个简单的timed_execution

You can provide a simple timed_execution class using various c++11 mechanisms

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_;
};

要在特定时间段内异步运行该函数,您只需创建此类的一个实例:

To run the function asynchronously with a certain period, you'll simply create an instance of this class:

int main() {
    timed_execution t(foo,std::chrono::milliseconds(2000));

    std::this_thread::sleep_for(std::chrono::seconds(60));
    return 0;
}

请在此处查看在线示例.

使用模板/可变模板在顶部提供实际要执行的函数的参数和返回类型,似乎是改进timed_execution类并按照以下方式选择timer类的一个好主意: /p>

Making use of templates/variadic templates to provide the actually to be executed function's parameters and return types on top, seems to be a good idea to improve the timed_execution class and go for a timer class as folows:

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()函数实例化


And have a separate make_timer() function to instantiate it

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;
}

这篇关于如何使用C ++ 11使函数在所需的时间执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆