std::shared_mutex和std::mutex的性能对比(banchmark)
原文作者:@玄冬Wong
转载请注明原文出处:http://aigo.iteye.com/blog/2296462
key world: std::shared_mutex、std::mutex、performance、benchmark、性能测试
shared_mutex的适用场景比较特殊:一个或多个读线程同时读取共享资源,且只有一个写线程来修改这个资源,这种情况下才能从shared_mutex获取性能优势。
cppreference文档
http://en.cppreference.com/w/cpp/thread/shared_mutex
Shared mutexes are usually used in situations when multiple readers can access the same resource at the same time without causing data races, but only one writer can do so.
测试代码:
注意,VC第一个支持shared_mutex的版本是VS2015 update2
测试结果:
2线程抢占
[test_mutex]
thread count:2
result:10000000 cost:1348ms temp:10000000
[test_shared_mutex]
thread count:2
result:10000000 cost:699ms temp:10000000
4线程抢占
[test_mutex]
thread count:4
result:10000000 cost:2448ms temp:10000000
[test_shared_mutex]
thread count:4
result:10000000 cost:1233ms temp:10000000
8线程抢占
[test_mutex]
thread count:8
result:5000000 cost:2452ms temp:5000000
[test_shared_mutex]
thread count:8
result:5000000 cost:1123ms temp:3231860
结论:
在多个只读线程和一个写线程的情况下,shared_mutex比mutex快一倍。
PS:std::shared_mutex和std::mutex分别对应java中的ReentrantReadWriteLock、ReentrantLock。