this_thread::sleep_for
- std::this_thread::sleep_for() 是 C++ 中的一个函数,它使当前线程暂停执行指定的时间。该函数接受一个时间段作为参数,指定线程需要休眠的时间长度。
- 在暂停线程执行时,会让出当前线程的时间片,但并不会释放线程占用的资源。线程在休眠期间仍然会占用系统分配给它的资源,若在资源有限的环境中使用大量的休眠操作,可能会造成资源的浪费和效率问题
#include <chrono> // 操作时间
#include <thread>
int main(int argc, char** argv)
{
std::this_thread::sleep_for(std::chrono::milliseconds(3)); // 毫秒
std::this_thread::sleep_for(std::chrono::seconds(3)); // 秒
std::this_thread::sleep_for(std::chrono::minutes(3)); // 分钟
std::this_thread::sleep_for(std::chrono::hours(3)); // 小时
}
boost::this_thread::sleep
该函数将阻塞当前线程的执行,在睡眠期间不会占用系统资源,但会挂起当前线程的执行。因此,在使用该函数时应谨慎考虑应用的需要以及其他的线程和资源使用情况。
#include <boost/thread/thread.hpp>
boost::this_thread::sleep(boost::posix_time::seconds(3));
boost::this_thread::sleep(boost::posix_time::minutes(3));
boost::this_thread::sleep(boost::posix_time::hours(3));