← 模式
休眠 (Sleep)
123456789101112 | #include <chrono> #include <thread> using namespace std::literals::chrono_literals; int main() { std::chrono::milliseconds sleepDuration(20); std::this_thread::sleep_for(sleepDuration); std::this_thread::sleep_for(5s); } |
此模式采用 CC0 公共领域贡献 许可。
需要 c++11 或更新版本。
意图
将线程的执行阻塞一段给定的时间。
描述
在第 7 行,我们创建了一个 std::chrono::milliseconds
对象来表示要休眠的毫秒数(也可以使用其他时间单位)。在第 8 行,对 std::this_thread::sleep_for
的调用将阻塞当前线程的执行,其时长至少为给定的时间。
在第 10 行,我们通过使用秒的后缀 s
来表示一个时间段,以此演示了 C++14 的时间段字面量后缀的用法。为了使用这些后缀,必须加上第 4 行的 using
指令。