原文作者:@玄冬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。