且构网

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

我们如何使用C ++中的chronicle语句创建一个循环?

更新时间:2022-12-09 10:18:05

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

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