std::shared_mutex::lock
From cppreference.com
< cpp | thread | shared mutex
| void lock(); |
(C++17以降) | |
shared_mutex を専有所有権で取得します。他のスレッドが同じ shared_mutex に対して専有ロックまたは共有ロックを保持している場合、lock の呼び出しは、そのようなすべてのロックが解放されるまで実行をブロックします。shared_mutex が専有モードでロックされている間は、他のいかなる種類のロックも保持することはできません。
lock が、すでにいずれかのモード(専有または共有)で shared_mutex を所有しているスレッドによって呼び出された場合、動作は未定義です。同じミューテックスに対する以前の unlock() 操作は、この操作と synchronizes-with(std::memory_order で定義される)します。
目次 |
[編集] パラメータ
(なし)
[編集] 戻り値
(なし)
[編集] 例外
エラーが発生した場合、および lock がその仕様を満たすのを妨げる基盤となるオペレーティングシステムからのエラーを含め、std::system_error をスローします。例外がスローされた場合、ミューテックスはロックされません。
[編集] 注記
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
[編集] 関連事項
| ミューテックスをロックしようとします。ミューテックスが利用できない場合は戻ります (public メンバ関数) | |
| ミューテックスをアンロックします (public メンバ関数) | |
| 共有所有権のためにミューテックスをロックします。ミューテックスが利用できない場合はブロックします (public メンバ関数) |