不可预测的C ++睡眠/等待行为

问题描述 投票:3回答:1

我必须做一些愚蠢的事情,因为我从这个简单的睡眠代码中得到了最奇怪的行为。最初,我使用std :: this_thread :: sleep_for并获得了相同的结果,但假定它一定是某些线程异常。但是,在等待下面的代码时,我看上去似乎有些混乱。与clang ++或g ++相同的结果。我在使用Debian并在命令行上进行编译。

预期的行为:关机3 ... [等待一秒钟] 2 ... [等待一秒钟] 1 ... [等待一秒钟;程序出口]

实际行为:[3秒钟的长时间等待]在3 ... 2 ... 1 ...中关闭[程序退出]

#include<chrono>
#include<iostream>

void Sleep(int i) {
    auto start = std::chrono::high_resolution_clock::now();
    auto now = std::chrono::high_resolution_clock::now();
    while (std::chrono::duration_cast<std::chrono::seconds>(now-start).count() < i)
        now = std::chrono::high_resolution_clock::now();
}

void ShutdownCountdown(int i) {
    if (i <= 0) return;

    std::cout << "Shutting down in ";
    for (; i != 0; --i) {
        std::cout << i << "... ";
        Sleep(1);
    }
    std::cout << std::endl << std::endl;
}

int main (int argc, char *argv[]) {
    ShutdownCountdown(3);

    return 0;
}
c++ sleep
1个回答
1
投票
#include<chrono>
#include<iostream>

void Sleep(int i) {
auto start = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
while (std::chrono::duration_cast<std::chrono::seconds>(now-start).count() < i)
    now = std::chrono::high_resolution_clock::now();
}

void ShutdownCountdown(int i) {
if (i <= 0) return;

std::cout << "Shutting down in "<<std::flush;
for (; i != 0; --i) {
    std::cout << i << "... "<<std::flush;
    Sleep(1);
}
std::cout << std::endl << std::endl;
}

int main (int argc, char *argv[]) {
ShutdownCountdown(3);

return 0; 
}
© www.soinside.com 2019 - 2024. All rights reserved.