如何在C 中添加代码延迟



我想添加一个延迟,以便一行运行,然后在短延迟后,第二行将运行。我是C 的新手,所以我不确定如何做到这一点。因此,理想情况下,在下面的代码中,它将打印"加载...",并至少等待1-2秒,然后再次打印"加载..."。目前,它瞬间打印而不是等待。

cout << "Loading..." << endl;
// The delay would be between these two lines. 
cout << "Loading..." << endl; 

在C 11中,您可以使用此线程和Crono进行:

#include <chrono>
#include <thread>
...
using namespace std::chrono_literals;
...
std::this_thread::sleep_for(2s);

要模拟'``工作中的报告'',您可能会考虑:

// start thread to do some work
m_thread = std::thread( work, std::ref(*this)); 
// work-in-progress report
std::cout << "nn  ... " << std::flush;
for (int i=0; i<10; ++i)  // for 10 seconds
{
   std::this_thread::sleep_for(1s); // 
   std::cout << (9-i) << '_' << std::flush; // count-down
}
m_work = false; // command thread to end
m_thread.join(); // wait for it to end

输出:

... 9_8_7_6_5_4_3_2_2_1_0 _

在10,175,240 US之后被遗弃的工作

概述:方法"工作"没有"完成",而是收到了放弃操作并在超时退出的命令。(成功的测试)

代码使用Chrono和Chrono_literals。

在温顿OS

#include <windows.h>
Sleep( sometime_in_millisecs );   // note uppercase S

在Unix Base OS

#include <unistd.h>
unsigned int sleep(unsigned int seconds);
#include <unistd.h>
int usleep(useconds_t usec); // Note usleep - suspend execution for microsecond intervals

您想要unistd.hsleep(unsigned int seconds)函数。在cout语句之间调用此功能。

最新更新