C++標準執行緒庫之當前執行緒管理
阿新 • • 發佈:2018-12-16
有時需要對當前執行的子執行緒進行一些額外的處理,如:使執行緒休眠一段時間,再次排程等。C++11標準庫提供了管理當前執行緒的函式,這些函式都定義於名稱空間this_thread
1. 獲取當前執行緒的識別符號
#include <thread>
inline thread::id std::this_thread::get_id();
// 返回當前執行緒id
#include <iostream>
#include <thread>
void func()
{
std::cout << "work thread id: " << std::this_thread::get_id() << std::endl;
}
int main()
{
std::thread thread(func);
thread.join();
return 0;
}
2. 執行緒重新排程
#include <thread>
inline void std::this_thread::yield();
// 使當前執行緒進入執行緒佇列,重新進行排程,來允許其他執行緒執行。
// 依賴於底層的系統排程機制和系統狀態。
需要注意的是,雖然t1執行緒重新排程,但是t2執行緒也不一定能先於t1輸出。
3. 執行緒睡眠
#include <thread>
template<typename _Rep, typename _Period>
inline void std::this_thread::sleep_for(const chrono::duration<_Rep, _Period>& __rtime);
// 只要知道其引數一個時間間隔,後續會介紹這個新時間類
// 可以使當前執行緒休眠一段時間
template<typename _Clock, typename _Duration>
inline void std::this_thread:: sleep_until(const chrono::time_point<_Clock, _Duration>& __atime);
// 只要知道其引數一個時間點,後續會介紹這個新時間類
// 可以使當前執行緒休眠到某個時間點
#include <iostream>
#include <thread>
// 用到了時間函式, 後續會介紹
// C++14標準的
using namespace std::chrono_literals;
void func()
{
// 2s是一個運算子過載函式,這裡表示2秒,且是真實時間,後續會介紹
std::this_thread::sleep_for(2s);
std::cout << "thread 1." << std::endl;
}
int main()
{
std::thread t(func);
t.join();
return 0;
}
這裡需要用到新時間類,這個時間類提供了與程式碼執行時間無關的時間測量(穩定時鐘),對於超時是非常重要的,後續會專門談到。