多线程编程C++++++++++++第10课(共享锁)

故事是这样的,为了提高效率,当多个线程在读取某个内存资源的时候,如果使用互斥锁或者递归锁的话,其他线程必须等待该线程结束,释放锁才能读取该内存资源。但假如该线程只读取不写的话,那能不能让其他线程也来一起读。共享锁:
#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值