前言:
C++ 17开始,引入了两个新的同步组件, shared_mutex 和 shared_lock ,这两个组件的一个典型使用案例就是实现读写锁。
原语:
shared_mutex , 一个提供让多个线程都可以同时获取能力的mutex。
shared_mutx提供了两套接口:
Exclusive locking | |
lock | locks the mutex, blocks if the mutex is not available (public member function) |
try_lock | tries to lock the mutex, returns if the mutex is not available (public member function) |
unlock | unlocks the mutex (public member function) |
Shared locking | |
lock_shared | locks the mutex for shared ownership, blocks if the mutex is not available (public member function) |
try_lock_shared | tries to lock the mutex for shared ownership, returns if the mutex is not available (public member function) |
unlock_shared | unlocks the mutex (shared ownership) (public member function) |
其中 exclusive locking 接口让 shared_mutex 的表现和 std::mutex 一模一样,只能被一个线程持有。
而shared locking 接口让 shared_mutex 可以被多个线程同时持有而不会阻塞任何一个线程。
但是,如果任何一个线程使用了 exclusive locking接口进行加锁,那么其他使用 shared locking进行加锁的线程都会被阻塞。
shared_lock
?
读写锁的实现
了解了 shared_mutex 的特点以后,我们可以推出如下读写锁的常用写法:
std::shared_mutex sharedMtx;void readResource(){//使用shared_lock确保使用 shared_mutex 的 shared locking 接口,进而实现shared加锁std::shared_lock<std::shared_mutex> lock(sharedMtx); //read resource
}void writeResource(){std::unique_lock<std::shared_mutex> lock(sharedMtx);//write resource
}
小结:
shared_mutex 的特别之处就是其提供了两套接口,一套是exclusive的,这让shared_mutex工作起来像std::mutex一样,另一套是shared的,这套接口让std::mutex工作在share模式下。