std::shared_lock<Mutex>::lock
来自cppreference.com
< cpp | thread | shared lock
void lock(); | (C++14 起) | |
以共享模式锁定关联互斥体。相当于调用 mutex()->lock_shared()。
目录 |
[编辑]参数
(无)
[编辑]返回值
(无)
[编辑]异常
- mutex()->lock_shared() 抛出的任何异常。
- 若无关联互斥体,则抛出以 std::errc::operation_not_permitted 为错误码的 std::system_error。
- 若关联互斥体已被此
shared_lock
锁定(即 owns_lock 返回true
),则返回以 std::errc::resource_deadlock_would_occur 为错误码的 std::system_error。
[编辑]示例
本节未完成 原因:展示有意义的 shared_lock::lock 用法 |
运行此代码
#include <iostream>#include <mutex>#include <shared_mutex>#include <string>#include <thread> std::string file ="原始内容。";// 模拟一个文件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<<"读者 #"<< id <<" 读取的内容: "<< content <<'\n';} void write_content(){{std::lock_guard file_lock(file_mutex); file ="新内容";}std::lock_guard output_lock(output_mutex);std::cout<<"已保存新内容。\n";} int main(){std::cout<<"两个读者读取文件。\n"<<"一个写者与它们竞争。\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<<"已完成前几个文件操作。\n"; reader1 =std::thread{read_content, 3}; reader1.join();}
可能的输出:
两个读者读取文件。 一个写者与它们竞争。 读者 #1 读取的内容: 原始内容。 读者 #2 读取的内容: 原始内容。 已保存新内容。 已完成前几个文件操作。 读者 #3 读取的内容: 新内容
[编辑]参阅
尝试锁定关联的互斥体 (公开成员函数) | |
解锁关联的互斥体 (公开成员函数) |