std::shared_lock<Mutex>:: lock
From cppreference.net
<
cpp
|
thread
|
shared lock
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::shared_lock
| Member functions | ||||
| Shared locking | ||||
|
shared_lock::lock
|
||||
| Modifiers | ||||
| Observers | ||||
| Non-member functions | ||||
|
void
lock
(
)
;
|
(C++14以降) | |
関連付けられたミューテックスを共有モードでロックします。実質的に mutex ( ) - > lock_shared ( ) を呼び出します。
目次 |
パラメータ
(なし)
戻り値
(なし)
例外
- mutex ( ) - > lock_shared ( ) によってスローされる例外。
- 関連付けられたミューテックスが存在しない場合、 std::system_error が std::errc::operation_not_permitted のエラーコードで送出される。
-
関連付けられたミューテックスが既にこの
shared_lockによってロックされている場合(すなわち、 owns_lock が true を返す場合)、 std::system_error がエラーコード std::errc::resource_deadlock_would_occur でスローされる。
例
|
このセクションは不完全です
理由: shared_lock::lock の意味のある使用例を示す |
このコードを実行
#include <iostream> #include <mutex> #include <shared_mutex> #include <string> #include <thread> std::string file = "Original content."; // ファイルをシミュレート std::mutex output_mutex; // 出力操作を保護するmutex std::shared_mutex file_mutex; // リーダー/ライター mutex void read_content(int id) { std::string content; { std::shared_lock lock(file_mutex, std::defer_lock); // 最初はロックしない lock.lock(); // ここでロック content = file; } std::lock_guard lock(output_mutex); std::cout << "Contents read by reader #" << id << ": " << content << '\n'; } void write_content() { { 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_content, 1}; std::thread reader2{read_content, 2}; std::thread writer{write_content}; reader1.join(); reader2.join(); writer.join(); std::cout << "The first few operations to file are done.\n"; reader1 = std::thread{read_content, 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
関連項目
|
関連付けられたミューテックスのロックを試行する
(public member function) |
|
|
関連付けられたミューテックスをアンロックする
(public member function) |