HOWTO · C++

在 C++ 中添加定时延迟

本教程将为你提供有关在 C++ 程序中添加定时延迟的简要指南。

本页内容

本教程将为你提供有关在 C++ 程序中添加定时延迟的简要指南。

这可以使用 C++ 库为我们提供的一些函数以多种方式完成。我们将讨论一些功能及其工作演示。

计算机程序中的任何进程、任务或线程都可以休眠或变为非活动状态。这意味着进程的执行可以在它处于睡眠状态时暂停。

当休眠间隔期满或信号或中断导致执行恢复时,将恢复执行。为此目的有不同的方法:

  1. sleep() 系统调用
  2. usleep() 方法
  3. sleep_for() 方法
  4. sleep_until() 方法

在 C++ 中使用 sleep() 系统调用添加定时延迟

sleep 系统调用可以使程序(任务、进程或线程)进入睡眠状态。典型的 sleep 系统调用中的 time 参数表明程序需要睡眠或保持非活动状态的时间。

C++ 语言没有睡眠功能。此功能由特定于操作系统的文件提供,例如 Linux 的 unistd.h 和 Windows 的 Windows.h

要在 Linux 或 UNIX 操作系统上使用 sleep() 函数,我们必须在程序中包含 "unistd.h" 头文件。

函数原型

unsigned sleep(unsigned seconds);

它需要我们需要暂停执行的参数秒数,如果成功返回执行,则返回 0。如果睡眠在两者之间被中断,则返回总时间减去中断时间。

例子:

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
  cout << "Before sleep call " << endl;
  cout.flush();
  sleep(9);
  cout << "After sleep call" << endl;

  return 0;
}

输出:

Before sleep call
After sleep call

在输出中,我们打印了两条语句。打印第一个后,编译器等待 9 秒,然后打印另一个。读者应该执行程序来观察这个延迟。

在 C++ 中使用 usleep() 函数添加定时延迟

头文件 unistd.h 中的另一个函数是 usleep(),它允许你暂停程序的执行一段时间。该操作与前面描述的 sleep() 函数相同。

函数 usleep() 将调用线程的执行暂停 useconds microseconds 或直到发送中断执行的信号。

函数原型

int usleep(useconds_t useconds);

此函数将需要暂停执行的微秒数作为参数,如果成功恢复,则返回 0,如果发生故障,则返回 -1。

例子:

#include <unistd.h>

#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
  cout << "Hello ";
  cout.flush();
  usleep(10000);
  cout << "World";
  cout << endl;

  return 0;
}

输出:

Before Usleep Call
After Usleep call

正如你在上面的代码片段中所看到的,我们在打印两个语句之间提供了 10000 微秒的等待时间。

在 C++ 11 中,我们提供了使线程休眠的特定函数。为此目的有两种方法,sleep_forsleep_until

让我们讨论这两种方法:

使用 sleep_for() 函数在 C++ 中添加定时延迟

sleep_for () 函数在 <thread> 头文件中定义。sleep_for () 函数在睡眠持续时间中指定的持续时间内暂停当前线程的执行。

由于调度活动或资源争用延迟,此功能可能会阻塞超过提供的时间段。

函数原型

template <class Rep, class Period>
void sleep_for(const std::chrono::duration<Rep, Period>& sleep_duration);

例子:

#include <chrono>
#include <iostream>
#include <thread>
using namespace std;

int main() {
  cout << "Hello I'm here before waiting" << endl;
  this_thread::sleep_for(chrono::milliseconds(10000));
  cout << "I Waited for 10000 ms\n";
}

输出:

Hello I'm here before waiting
I Waited for 10000 ms

在上面的代码片段中,我们让主线程休眠 10000 毫秒,这意味着当前线程将阻塞 10000 毫秒,然后恢复执行。

在 C++ 中使用 sleep_until() 函数添加定时延迟

<thread> 头文件定义了这个函数。sleep_until () 方法停止线程运行,直到经过睡眠时间。

由于调度活动或资源争用延迟,此功能与其他功能一样,可能会阻塞超过指定时间。

函数原型

template <class Clock, class Duration>
void sleep_until(const std::chrono::time_point<Clock, Duration>& sleep_time);

它将需要阻塞线程的周期作为参数,并且不返回任何内容。

例子:

#include <chrono>
#include <iostream>
#include <thread>
using namespace std;

int main() {
  cout << "Hello I'm here before waiting" << endl;
  std::this_thread::sleep_until(std::chrono::system_clock::now()
                                    std::chrono::seconds(3));
  cout << "I Waited for 3 seconds\n";
}

输出:

Hello I'm here before waiting
I Waited for 2 seconds