c++ this_thread::sleep_for
时间: 2024-01-14 18:09:35 浏览: 36
`this_thread::sleep_for` 是 C++11 标准库中的一个函数,可以让当前线程睡眠一段时间。其函数原型为:
```cpp
template< class Rep, class Period >
void sleep_for( const std::chrono::duration<Rep,Period>& sleep_duration );
```
其中 `sleep_duration` 参数表示需要睡眠的时间,可以是任意长度的时间段,例如 `std::chrono::milliseconds(500)` 表示需要睡眠 500 毫秒。
使用示例:
```cpp
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
std::cout << "Sleeping for 1 second..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Done!" << std::endl;
return 0;
}
```
执行上述代码会输出 "Sleeping for 1 second...",然后等待 1 秒钟后输出 "Done!"。
相关问题
c++ this_thread::sleep_until
`this_thread::sleep_until` 是 C++11 标准库中的一个函数,可以让当前线程睡眠直到指定的时间点。其函数原型为:
```cpp
template< class Clock, class Duration >
void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time );
```
其中 `sleep_time` 参数表示需要等待的时间点,可以使用 `std::chrono::system_clock::now()` 获取当前时间后再加上一个时间段得到。
使用示例:
```cpp
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
auto now = std::chrono::system_clock::now();
auto wakeup_time = now + std::chrono::seconds(5);
std::cout << "Sleeping until " << std::chrono::system_clock::to_time_t(wakeup_time) << "..." << std::endl;
std::this_thread::sleep_until(wakeup_time);
std::cout << "Woke up at " << std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()) << std::endl;
return 0;
}
```
执行上述代码会输出 "Sleeping until [指定时间]...",然后等待直到指定的时间点后输出 "Woke up at [实际醒来的时间]"。
this_thread::sleep_for
this_thread::sleep_for 是 C++11 中的一个函数,用于让当前线程休眠一段时间。它的参数是一个 std::chrono::duration 类型的时间段,可以指定秒、毫秒、微秒等单位。例如,this_thread::sleep_for(std::chrono::milliseconds(100)) 表示让当前线程休眠 100 毫秒。