手撕读写锁性能测试

测试代码

基本思路
先用CountDownLatch (详见下节,并发用具) 同步子线程创建,然后,摁下计时器一次,开始测试。
再用另一个CountDownLatch 同步子线程完成任务的情况,最后再按一下计时器。

配置:
1个写线程,7个读线程。同时,内部控制读写次数,为了方便体现读写锁的性能与互斥锁的性能对比,直接调整内部循环的限制次数即可。

粗略的结果
在写的次数比读的次数要少得多时,读写锁性能比互斥锁要高。
在写得次数比读得次数差不多时,互斥锁性能比读写锁略高。

但是在开启代码优化后,只有写者数量少于读者数量的两个数量级左右,读写锁的性能才开始体现出来。

CountDownLatch startLatch(1);
CountDownLatch endLatch(8);
ReadWriteLock mtx;

int g_count = 0;

void write_something() {
   
	startLatch.wait();

	int count = 1000; // thread_local
	do {
   
		WriterLockGuard lock(::mtx);
		g_count++;
	} while (--count);

	endLatch.down();
}

void read_something() {
   
	startLatch.wait();

	int count = 100000; // thread_local
	do {
   

#ifndef TEST_RWLOCK
		WriterLockGuard lock(::mtx);
#else
		ReaderLockGuard lock(::mtx);
#endif

	} while (--count);

	endLatch.down();
}

int main()
{
   	
	using namespace std::chrono;
	std::vector<std
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值