詳解C++11 執行緒休眠函式
阿新 • • 發佈:2020-10-13
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 執行緒休眠函式的資料請關注我們其它相關文章!