在 C++ 中暂停程序执行 5 秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23609507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:30:22  来源:igfitidea点击:

Pause program execution for 5 seconds in c++

c++

提问by charlotte

I want to pause the execution of c++ program for 5 seconds. In android Handler.postDelayed has the required functionality what I am looking for. Is there anything similar to that in c++?

我想暂停 C++ 程序的执行 5 秒钟。在 android Handler.postDelayed 中具有我正在寻找的所需功能。在 C++ 中有类似的东西吗?

回答by const_ref

#include <iostream>
#include <chrono>
#include <thread>

int main()
{
    std::cout << "Hello waiter" << std::endl;
    std::chrono::seconds dura( 5);
    std::this_thread::sleep_for( dura );
    std::cout << "Waited 5s\n";
}

this_thread::sleep_forBlocks the execution of the current thread for at least the specified sleep_duration.

this_thread::sleep_for至少在指定的 sleep_duration 内阻止当前线程的执行。

回答by peterh - Reinstate Monica

You can to this on the pure C level, because C api calls are usable also from C++. It eliminiates the problem if you actual c++ library didn't contained the needed std:chronoor std::this_thread(they differs a little bit).

您可以在纯 C 级别进行此操作,因为 C api 调用也可从 C++ 使用。如果您实际的 C++ 库不包含所需的std:chronostd::this_thread(它们略有不同),它就可以消除问题。

The C api of most OSes contains some like a sleeping function, although it can be also different. For example, on posixen, there is the sleep()API call in the standard C library, and you can use this from C++ as well:

大多数操作系统的 C api 包含一些类似于睡眠的功能,尽管它也可以不同。例如,在 posixen 上,sleep()标准 C 库中有API 调用,您也可以在 C++ 中使用它:

#include <unistd.h>

int main() {
   sleep(5);
   return;
}

Or you can use usleep()is you want a better precision as seconds. usleep()can sleep for microsecond precision.

或者你可以使用usleep()你想要更好的精度作为秒。usleep()可以休眠微秒精度。

On windows, you can use the Sleep(int usec)call, which is with big 'S', and uses milliseconds.

在 Windows 上,您可以使用Sleep(int usec)带有大 ' S' 并使用毫秒的调用。