std::shared_mutex::lock
来自cppreference.com
<tbody>
</tbody>
void lock(); |
(C++17 起) | |
获取 shared_mutex 的独占所有权。如果有另一线程已持有同一 shared_mutex 上的独占锁或共享锁,那么对 lock 的调用将阻塞执行直到所有这些锁都被释放。当 shared_mutex 被以独占模式锁定时,不可持有任何种类的其他锁。
如果 lock 被已经以任何模式(独占或共享)拥有此 shared_mutex 的线程调用,则其行为未定义。
在同一互斥体上之前的 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() << " 见到: ";
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 见到: 43 3 3 4 46 5 6 7 7 8 9 51 10 11 11 12 -999
144541248 见到: 2 44 3 4 46 5 6 7 7 8 9 51 10 11 11 12 -999
110970432 见到: 42 2 3 45 4 5 47 6 7 8 8 9 10 11 11 12 -999
119363136 见到: 42 2 3 4 46 5 6 7 7 8 9 9 10 11 11 12 12 -999
136148544 见到: 2 44 3 4 46 5 6 48 7 8 9 51 10 11 11 12 12 -999
参阅
| 尝试锁定互斥体,若互斥体不可用则返回 (公开成员函数) | |
| 解锁互斥体 (公开成员函数) | |
| 为共享所有权锁定互斥体,若互斥体不可用则阻塞 (公开成员函数) |