详解C++11 线程休眠函数
C++ 11之前并未提供专门的休眠函数。c语言的sleep、usleep其实都是系统提供的函数,不同的系统函数的功能还有些差异。
在Windows系统中,sleep的参数是毫秒。
sleep(2*1000); //sleep for 2 seconds
在类Unix系统中,sleep()函数的单位是秒。
sleep(2); //sleep for 2 seconds
从C++11开始,中C++标准库提供了专门的线程休眠函数,使得你的代码可以独立于不同的平台。
std::this_thread::sleep_for std::this_thread::sleep_untill
1. 让线程休眠一段时间
std::this_thread::sleep_for用于Block当前线程一段时间。
template< class Rep, class Period > void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration );
sleep的时间间隔从纳秒到小时都有具体的定义。
std::chrono::nanoseconds std::chrono::microseconds std::chrono::milliseconds std::chrono::seconds std::chrono::minutes std::chrono::hours
比如我们想要一个线程休眠100ms。
std::this_thread::sleep_for(std::chrono::milliseconds(100));
我们想要一个线程休眠1分钟:
std::this_thread::sleep_for(std::chrono::minutes(1));
完整的代码示例:
#include <iostream> #include <chrono> #include <thread> int main() { std::cout << "Hello waiter\n" << std::flush; auto start = std::chrono::high_resolution_clock::now(); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> elapsed = end-start; std::cout << "Waited " << elapsed.count() << " ms\n"; }
输出:
Hello waiter
Waited 2000.12 ms
2. 休眠直至到一个时间点
template< class Clock, class Duration > void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time )
sleep_until会阻塞当前线程直至未来某个时间点到达。
#include <iostream> #include <thread> #include <chrono> // Print Current Time void print_time_point(std::chrono::system_clock::time_point timePoint) { std::time_t timeStamp = std::chrono::system_clock::to_time_t(timePoint); std::cout << std::ctime(&timeStamp) << std::endl; } void threadFunc() { std::cout<<"Current Time :: "; // Print Current Time print_time_point(std::chrono::system_clock::now()); // create a time point pointing to 10 second in future std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now() + std::chrono::seconds(10); std::cout << "Going to Sleep Until :: "; print_time_point(timePoint); // Sleep Till specified time point // Accepts std::chrono::system_clock::time_point as argument std::this_thread::sleep_until(timePoint); std::cout<<"Current Time :: "; // Print Current Time print_time_point(std::chrono::system_clock::now()); } int main() { std::thread th(&threadFunc); th.join(); return 0; }
程序输出:
Current Time :: Sun Oct 11 02:57:38 2020
Going to Sleep Until :: Sun Oct 11 02:57:48 2020
Current Time :: Sun Oct 11 02:57:48 2020
参考材料
1.https://baike.baidu.com/item/sleep%E5%87%BD%E6%95%B0/6735027
2.https://thispointer.com/how-to-put-a-thread-to-sleep-in-c11-sleep_for-sleep_until/
以上就是详解C++11 线程休眠函数的详细内容,更多关于C++11 线程休眠函数的资料请关注我们其它相关文章!
赞 (0)