std::shared_mutex::lock
來自 cppreference.com
< cpp | thread | shared mutex
void lock(); |
(C++17 起) | |
獲取對 shared_mutex
的獨佔所有權。如果其他執行緒持有相同 shared_mutex
的獨佔鎖或共享鎖,則呼叫 lock
將會阻塞執行,直到所有此類鎖都被釋放。當 shared_mutex
以獨佔模式鎖定後,不能持有任何其他型別的鎖。
如果一個執行緒已經以任何模式(獨佔或共享)擁有 shared_mutex
,並再次呼叫 lock
,則行為是未定義的。在同一互斥量上先前的 unlock() 操作與此操作同步(如 std::memory_order 中定義)。
目錄 |
[編輯] 引數
(無)
[編輯] 返回值
(無)
[編輯] 異常
當發生錯誤時丟擲 std::system_error,包括底層作業系統阻止 lock
滿足其規範的錯誤。在丟擲任何異常的情況下,互斥量都不會被鎖定。
[編輯] 注意
lock()
通常不直接呼叫:std::unique_lock、std::scoped_lock 和 std::lock_guard 用於管理獨佔鎖定。
[編輯] 示例
執行此程式碼
#include <chrono> #include <iostream> #include <mutex> #include <shared_mutex> #include <syncstream> #include <thread> #include <vector> std::mutex stream_mutx; void print(auto const& v) { std::unique_lock<std::mutex> lock(stream_mutx); std::cout << std::this_thread::get_id() << " saw: "; for (auto e : v) std::cout << e << ' '; std::cout << '\n'; } int main() { using namespace std::chrono_literals; constexpr int N_READERS = 5; constexpr int LAST = -999; std::shared_mutex smtx; int product = 0; auto writer = [&smtx, &product](int start, int end) { for (int i = start; i < end; ++i) { auto data = i; { std::unique_lock<std::shared_mutex> lock(smtx); // better than: // smtx.lock(); product = data; } std::this_thread::sleep_for(3ms); } smtx.lock(); // lock manually product = LAST; smtx.unlock(); }; auto reader = [&smtx, &product] { int data = 0; std::vector<int> seen; do { { // better to use: std::shared_lock lock(smtx); // smtx.lock_shared(); data = product; } // smtx.unlock_shared(); seen.push_back(data); std::this_thread::sleep_for(2ms); } while (data != LAST); print(seen); }; std::vector<std::thread> threads; threads.emplace_back(writer, 1, 13); threads.emplace_back(writer, 42, 52); for (int i = 0; i < N_READERS; ++i) threads.emplace_back(reader); for (auto&& t : threads) t.join(); }
可能的輸出
127755840 saw: 43 3 3 4 46 5 6 7 7 8 9 51 10 11 11 12 -999 144541248 saw: 2 44 3 4 46 5 6 7 7 8 9 51 10 11 11 12 -999 110970432 saw: 42 2 3 45 4 5 47 6 7 8 8 9 10 11 11 12 -999 119363136 saw: 42 2 3 4 46 5 6 7 7 8 9 9 10 11 11 12 12 -999 136148544 saw: 2 44 3 4 46 5 6 48 7 8 9 51 10 11 11 12 12 -999
[編輯] 參閱
嘗試鎖定互斥體,如果互斥體不可用則返回 (公有成員函式) | |
解鎖互斥體 (公有成員函式) | |
以共享所有權鎖定互斥體,如果互斥體不可用則阻塞 (公有成員函式) |