C++20 semaphore
01 C++20 semaphore
下面是在 www.open-std.org
對 C++20 semaphore
的一點介紹內容。(semaphores、latch、barrier)
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1135r2.html
1
cppreference.com
中的標準庫頭文件 <semaphore>
中也給出了詳細定義。2。
C++20 中提供了兩個信號量類。(其實binary_semaphore僅僅是counting_semaphore的一個特例。)
信號量類名 | 含義 |
---|---|
counting_semaphore | 實現非負資源計數的信號量 |
binary_semaphore | 僅擁有二個狀態的信號量 |
cppreference.com
中給出的關於semaphore的定義如下:
// 概要
namespace std {
template<ptrdiff_t LeastMaxValue = /* 實現定義 */>
class counting_semaphore;
using binary_semaphore = counting_semaphore<1>;
}
// 類模板 std::counting_semaphore
namespace std {
template<ptrdiff_t LeastMaxValue = /* 實現定義 */>
class counting_semaphore {
public:
static constexpr ptrdiff_t max() noexcept;
constexpr explicit counting_semaphore(ptrdiff_t desired);
~counting_semaphore();
counting_semaphore(const counting_semaphore&) = delete;
counting_semaphore& operator=(const counting_semaphore&) = delete;
void release(ptrdiff_t update = 1);
void acquire();
bool try_acquire() noexcept;
template<class Rep, class Period>
bool try_acquire_for(const chrono::duration<Rep, Period>& rel_time);
template<class Clock, class Duration>
bool try_acquire_until(const chrono::time_point<Clock, Duration>& abs_time);
private:
ptrdiff_t counter; // 僅用於闡釋
};
}
std::counting_semaphore3
- counting_semaphore 是一個輕量同步元件,能控制對共享資源的訪問。不同於 std::mutex 、 counting_semaphore 允許同一資源有多於一個同時訪問,至少允許 LeastMaxValue 個同時的訪問者若LeastMaxValue 爲負則程序爲謬構。
- binary_semaphore 是 std::counting_semaphore 的特化的別名,其 LeastMaxValue 爲 1 。實現可能將 binary_semaphore 實現得比 std::counting_semaphore 的默認實現更高效。
counting_semaphore 含有由構造函數初始化的內部計數器。由調用 acquire() 與相關方法減少此計數器,而它通過調用 release() 增加。計數器爲零時, acquire() 阻塞該計數器直至它增加,但 try_acquire() 不阻塞; try_acquire_for() 與 try_acquire_until() 阻塞直至計數器增加或到達時限。
類似 std::condition_variable 的 wait() , counting_semaphore 的 try_acquire() 可能虛假地失敗。
std::counting_semaphore的主要接口
接口 | 含義 |
---|---|
release | 增加內部計數器併除阻獲取者 |
acquire | 減少內部計數器或阻塞到直至能如此 |
try_acquire | 嘗試減少內部計數器而不阻塞 |
try_acquire_for | 嘗試減少內部計數器,至多阻塞一段時長 |
try_acquire_until | 嘗試減少內部計數器,阻塞直至一個時間點 |
max | 返回內部計數器的最大可能值(靜態,常量) |
註解
如其名所示, LeastMaxValue 是最小的最大值,而非實際最大值。從而 max() 能產生大於 LeastMaxValue 的值。不同於 std::mutex , counting_semaphore 不捆綁到執行線程——能在不同於釋放信號量的線程獲取該信號量。能同時進行 counting_semaphore 上的所有操作而無需聯繫到任何特定的執行線程,除了不能同時執行,但能在一個不同的線程上執行析構函數。
信號量亦常用於發信/提醒而非互斥,通過初始化該信號量爲 0 從而阻塞嘗試 acquire() 的接收者,直至提醒者通過調用 release(n) “發信”。在此方面可把信號量當作 std::condition_variable 的替用品,通常它有更好的性能。