std::shared_mutex::lock_shared
来自 cppreference.cn
< cpp | thread | shared mutex
void lock_shared(); |
(C++17 起) | |
获得互斥的共享所有权。若另一线程以独占所有权保有该互斥,则到 lock_shared
的调用将阻塞执行,直到能获得共享所有权。
若已以任何模式(独占或共享)占有该 mutex
的线程调用 lock_shared
,则其行为未定义。
若已在共享模式下锁定该互斥的共享所有者数量超过了实现定义的最大值,则 lock_shared
阻塞执行,直到共享所有者数量减少。所有者的最大数量保证至少为 10000。
先前对同一互斥的 unlock() 操作与此操作同步于(定义于 std::memory_order)。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
(无)
[编辑] 异常
当发生错误时抛出 std::system_error,包括底层操作系统会阻止 lock
满足其规范的错误。若抛出任何异常,则互斥未被锁定。
[编辑] 注意
通常不直接调用 lock_shared()
:使用 std::shared_lock 来管理共享锁定。
[编辑] 示例
运行此代码
#include <chrono> #include <iostream> #include <mutex> #include <shared_mutex> #include <syncstream> #include <thread> #include <vector> std::mutex stream_mutx; void print(auto 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); 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 { { smtx.lock_shared(); // better to use: std::shared_lock lock(smtx); 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
[编辑] 参阅
锁定互斥体,如果互斥体不可用则阻塞 (公开成员函数) | |
尝试以共享所有权锁定互斥体,如果互斥体不可用则返回 (公开成员函数) | |
解锁互斥体(共享所有权) (公开成员函数) |