《探索C 多執行緒》 thread原始碼(二)

2021-07-30 17:06:52 字數 2426 閱讀 2962

分析thread的內部類id 和 命名空間this_thread。

this_thread中有四個函式,分別是:get_id()、yield()、sleep_for()、sleep_until(),它們的定義如下:

namespace this_thread 

_thrd_yield();

}inline void sleep_until(const stdext::threads::xtime *_abs_time)

_thrd_sleep(_abs_time);

}templateinline

void sleep_until( const chrono::time_point<_clock, _duration>& _abs_time)

templateinline

void sleep_for(const chrono::duration<_rep, _period>& _rel_time)

} // namespace this_thread

inline thread::id this_thread::get_id() _noexcept
解釋如下:

this_thread::get_id():返回當前執行緒;

this_thread::yield():讓出時間片(執行緒的狀態轉變:執行狀態—>可執行狀態);

(防止當前執行緒獨佔cpu資源而使得其他執行緒得不到響應,因此主動讓出搶到的時間片a,讓其他執行緒去搶奪時間片a,而當前執行緒不參與時間片a的搶奪。當時間片a被其他執行緒使用完後,由作業系統呼叫,當前執行緒再與其他執行緒一同搶奪下一時間片);

this_thread::sleep_for():使當前執行緒休眠指定時間(執行緒的狀態轉變:執行狀態—>休眠狀態—>可執行狀態);

this_thread::sleep_until():休眠當前執行緒,直到指定時間點到來(執行緒的狀態轉變:執行狀態—>休眠狀態—>可執行狀態);

再來看class id,其宣告和定義如下:

class thread::id 

templatebasic_ostream<_ch, _tr>& _to_text(basic_ostream<_ch, _tr>& _str)

size_t hash() const

private:

id(const thread& _thrd) : _thr(_thrd._thr) // 建構函式

id(_thrd_t _thrd) : _thr(_thrd) // 建構函式

_thrd_t _thr; // 私有變數

friend thread::id thread::get_id() const _noexcept;

friend thread::id this_thread::get_id() _noexcept;

friend bool operator==(thread::id _left, thread::id _right) _noexcept;

friend bool operator<(thread::id _left, thread::id _right) _noexcept;

};

inline bool operator==(thread::id _left, thread::id _right) _noexcept 

inline bool operator!=(thread::id _left, thread::id _right) _noexcept

inline bool operator<(thread::id _left, thread::id _right) _noexcept

inline bool operator<=(thread::id _left, thread::id _right) _noexcept

inline bool operator>(thread::id _left, thread::id _right) _noexcept

inline bool operator>=(thread::id _left, thread::id _right) _noexcept

// template struct specialization hash

template<>

struct hash: public unary_function

};

好了,大概就是這樣。這裡沒有太多好分析的,c++ 11 標準庫把底層都給封裝好了,用起來很方便,但是太細節的東西要追究起來就比較難。

若有理解失誤或表達不清的地方,還請大家多多指教,謝謝~

《探索C 多執行緒》 future原始碼(一)

在此之前的幾篇文章分別介紹和分析了c 11.0標準庫中支援多執行緒的幾個標頭檔案 那麼接下來乘熱打鐵,在這篇文章中將要分析的是 多執行緒的非同步操作。多執行緒的非同步操作原始碼在標頭檔案中。我們先來看一看中都定義了些什麼類 函式 classes future future error package...

《探索C 多執行緒》 future原始碼(二)

std promise promise物件可以儲存某一t型別的值,該值可以被future物件 可能在另乙個執行緒中 獲取,因此promise也提供了一種同步手段。在構造時,promise物件與乙個新的共享狀態 通常是std future 相關聯,他們可以儲存t型別的值或從std exception派...

c 多執行緒 原始碼3

在開發中經常會遇到執行緒的例子,如果某個後台操作比較費時間,我們就可以啟動乙個執行緒去執行那個費時的操作,同時程式繼續執行。在某些情況下可能會出現多個執行緒的同步協同的問題,下面的例子就展示了在兩個執行緒之間如何協同工作。這個程式的思路是共同做一件事情 從乙個arraylist中刪除元素 如果執行完...