故事是这样的,为了提高效率,当多个线程在读取某个内存资源的时候,如果使用互斥锁或者递归锁的话,其他线程必须等待该线程结束,释放锁才能读取该内存资源。但假如该线程只读取不写的话,那能不能让其他线程也来一起读。共享锁:
#include<share_mutex>
shared_mutex mux;
mux.shared_lock();
mux.unlock_shared();
可以使得多个线程一起读取。也可以进化为互斥锁,条件为:某个线程在读的过程中,想要写入,直接使用,mux.lock();其他线程这时候会堵塞不能访问,只能等待该线程mux.unlock();
#include <iostream>
#include <thread>
#include <mutex>
#include <shared_mutex>
#include <string>
/*
实现一个共享锁的案例,共享锁的原理:
当某个线程获取到该资源,进入临界区,使用共享锁share_lock 锁起来,
这个时候其线程是可以读取该临界区的资源的。
接着,当线程进行读线程的时候, 使用lock()进行互斥起来,其他线程无论是读还是写都不能进行
直到互斥锁释放
*/
using namespace std;
shared_mutex share_mux;
string name = "000";
void tid_Read() {
cout << "Read:" << this_thread::get_id() << endl;
//Resource
//上锁
share_mux.lock_shared();
for (int i = 0; i < 100000; i++)
{
cout << i << ":" << name << endl;
this_thread::sleep_for(500ms);
}
share_mux.unlock_shared();
//解锁
this_thread::sleep_for(1000ms);
}
void tid_write() {
cout << "Write:" << this_thread::get_id() << endl;
while (1) {
//写入操作
share_mux.lock();
name = "hcp";
this_thread::sleep_for(5ms);
share_mux.unlock();
this_thread::sleep_for(5ms);
}
this_thread::sleep_for(1000ms);
}
int main() {
cout << "I am main tid:" << this_thread::get_id() << endl;
//并发开线程
thread tid1(tid_Read);
thread tid2(tid_write);
thread tid3(tid_Read);
tid1.detach();
tid2.detach();
tid3.detach();
cout << name << endl;
getchar();
return 0;
}