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; // 保护输出操作的互斥锁 std::shared_mutex file_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
参见
|
尝试锁定关联的互斥量
(公开成员函数) |
|
|
解锁关联的互斥量
(公开成员函数) |