std::shared_mutex:: lock
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Exclusive locking | ||||
|
shared_mutex::lock
|
||||
| Shared locking | ||||
| Native handle | ||||
|
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); // 优于: // smtx.lock(); product = data; } std::this_thread::sleep_for(3ms); } smtx.lock(); // 手动加锁 product = LAST; smtx.unlock(); }; auto reader = [&smtx, &product] { int data = 0; std::vector<int> seen; do { { // 推荐使用: 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
另请参阅
|
尝试锁定互斥锁,若互斥锁不可用则立即返回
(公开成员函数) |
|
|
解锁互斥锁
(公开成员函数) |
|
|
以共享模式锁定互斥锁,若互斥锁不可用则阻塞
(公开成员函数) |