且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C ++ 11使函数在所需的时间执行

更新时间:2023-10-09 11:48:58

假设您希望每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;
}