std::shared_lock<Mutex>::lock
提供: cppreference.com
< cpp | thread | shared lock
void lock(); |
(C++14以上) | |
紐付けられているミューテックスを共有モードでロックします。 実質的に mutex()->lock_shared() を呼びます。
目次 |
[編集] 引数
(なし)
[編集] 戻り値
(なし)
[編集] 例外
- mutex()->lock_shared() によって投げられるあらゆる例外。
- 紐付けられているミューテックスがない場合、エラーコード std::errc::operation_not_permitted を持つ std::system_error。
- 紐付けられているミューテックスがこの
shared_lock
によってすでにロックされている (つまり、 owns_lock がtrue
を返す) 場合、エラーコード std::errc::resource_deadlock_would_occur を持つ std::system_error。
[編集] 例
This section is incomplete Reason: show a meaningful use of shared_lock::lock |
Run this code
#include <iostream> #include <mutex> #include <string> #include <shared_mutex> #include <thread> std::string file = "Original content."; // Simulates a file std::mutex output_mutex; // mutex that protects output operations. std::shared_mutex file_mutex; // reader/writer mutex void read(int id) { std::string content; { std::shared_lock lock(file_mutex, std::defer_lock); // Do not lock it first. lock.lock(); // Lock it here. content = file; } std::lock_guard lock(output_mutex); std::cout << "Contents read by reader #" << id << ": " << content << '\n'; } void write() { { std::lock_guard file_lock(file_mutex); file = "New content"; } std::lock_guard output_lock(output_mutex); std::cout << "New content saved.\n"; } int main() { std::cout << "Two readers reading from file.\n" << "A writer competes with them.\n"; std::thread reader1(read, 1); std::thread reader2(read, 2); std::thread writer(write); reader1.join(); reader2.join(); writer.join(); std::cout << "The first few operations to file are done.\n"; reader1 = std::thread(read, 3); reader1.join(); }
出力例:
Two readers reading from file. A writer competes with them. Contents read by reader #1: Original content. Contents read by reader #2: Original content. New content saved. The first few operations to file are done. Contents read by reader #3: New content
[編集] 関連項目
紐付けられているミューテックスのロックを試みます (パブリックメンバ関数) | |
紐付けられているミューテックスのロックを解除します (パブリックメンバ関数) |