我们如何使用C ++中的chronicle语句创建一个循环? [英] How can we make a loop with chronicle statement in C++?

查看:114
本文介绍了我们如何使用C ++中的chronicle语句创建一个循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我们如何做一个循环(例如while循环),while循环中的语句是基于时间的。

I was wondering how we could make a loop (a while-loop, for example) where the statement inside the while-loop be time-based.

为了更清楚,例如我想做一个while循环,我将每10秒输入一次。

To be more clear, for example I would like to make a while-loop which I will enter every 10 seconds.

伪代码将如下所示:

while (10 seconds have passed)
{
    //do Something
}

那么,如何才能使上述伪码真实? (我希望已经清楚了)

So, how could make the above pseudocode real? (I hope having been clear)

推荐答案

这不一定是直接的,因为,在某些情况下,线程等待调用可以比请求早唤醒。

This is not necessarily as straightforward as it sounds because, even though I don't think it is supposed to, in some situations thread waiting calls can wake up earlier than requested.

为了防止我发现有必要将等待代码放在一个循环中,以便当线程唤醒时,它检查整个时间是否已经过期。如果不是它重新进入睡眠:

To combat that I found it necessary to put the waiting code in a loop so that when the thread wakes up it checks if the whole time has expired. If not it re-enters the sleep:

using clock = std::chrono::steady_clock; // for an easier life

// set the wake-up time for 10 seconds in the future
auto timeout = clock::now() + std::chrono::seconds(10);

for(;;)
{
    // loop in-case of early wakeup
    while(clock::now() < timeout)
        std::this_thread::sleep_until(timeout);

    timeout += std::chrono::seconds(10); // reset timer

    // do something useful (like print the time)
    auto timer = std::time(0);
    std::cout << "loop: " << std::ctime(&timer) << '\n';
}

使用 std :: this_thread :: sleep_until )当等待 10 秒时,循环不消耗 CPU

By using std::this_thread::sleep_until() the loop doesn't consume CPU time while it is waiting for the 10 seconds to elapse.

这可以包装在一个整洁的小类,如下:

This can be wrapped up in a neat little class like this:

class wait_timer
{
    using clock = std::chrono::steady_clock;

    clock::duration time_to_wait;
    clock::time_point timeout = clock::now();

public:
    wait_timer(std::chrono::milliseconds ms)
    : time_to_wait(ms), timeout(clock::now() + ms) {}

    void wait()
    {
        while(clock::now() < timeout)
            std::this_thread::sleep_until(timeout);
        timeout += time_to_wait; // reset timer
    }
};

int main()
{
    // create it outside the loop so it doesn't
    // loose track of time every iteration
    wait_timer wt(std::chrono::seconds(2));

    for(;;)
    {
        wt.wait();

        // do something useful (like print the time)
        auto timer = std::time(0);
        std::cout << "loop: " << std::ctime(&timer) << '\n';
    }
}

这篇关于我们如何使用C ++中的chronicle语句创建一个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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