本文主要是介绍c++实现的一对锁的封装(挺有意思的),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在使用锁的时候,出现的最多的问题是由于忘记对锁的释放从而出现的各种死锁问题。所以经常会去检查对应的锁是否在之后的代码中得到合适的释放。前段时间学习到很巧妙的实现,即在构造函数中实现对锁的锁定,在析构函数中实现对锁的释放,这样只需要在使用锁的时候,定义一个锁,接下来即进入临界区,最后在退出对应的作用域的时候,自动调用析构函数,对应的锁自动释放, 对于一些锁的简单使用,还是比较不错的,个人觉得挺有意思的,拿出来和大家分享下。
----------------------------------------------------------------------------------------------------------------------------------------------------------------- class ThreadRWLock
- {
- public:
- ThreadRWLock(){
- pthread_rwlockattr_t attr;
- pthread_rwlockattr_init(&attr);
- pthread_rwlock_init(&_rw_lock, &attr);
- }
- ~ThreadRWLock(){
- pthread_rwlock_destory(&_rw_lock);
- }
- int AcquireRead(void){
- return pthread_rwlock_rdlock(&_rw_lock);
- }
- int AcquireWrite(void){
- return pthread_rwlock_wrlock(&_rw_lock);
- }
- int Release(void){
- return pthread_rwlock_unlock(&_rw_lock);
- }
- private:
- pthread_rwlock_t _rw_lock;
- };
----------------------------------------------------------------------------------------------------------------------------------------------------------------
//读锁的实现
- class ReadLocker
- {
- public:
- explicit ReadLocker(ThreadRWLock& rwlock): _lock_point(&rwlock)
- {
- _lock_point->AcquireRead();
- _is_lock = true;
- }
- ~ReadLocker(){
- if (_is_lock)
- _lock_point->Release();
- }
- void Lock(){
- if (!_is_lock)
- _lock_point->AcquireRead();
- _is_lock = true;
- }
- void Unlock(){
- if (_is_lock){
- _lock_point->Release();
- }
- _is_lock = false;
- }
- private:
- ThreadRWLock * _lock_point;
- bool is_lock;
- };
- void fun(void){
- ThreadRWLock lock;
- ReadLocker readlock(lock); //自动获取读锁
- /*
- 临界区
- */
- //退出作用域自动释放读锁
- }
//写锁的实现:
- class WriteLocker
- {
- public:
- explicit WriteLocker(ThreadRWLock& rwlock)
- : _lock_point(rwlock){
- _lock_point->AcquireWrite();
- _is_lock = true;
- }
- explicit WriteLocker(ThreadRWLock* rwlock)
- :_lock_point(rwlock){
- _lock_point->AcquireWrite();
- _is_lock = true;
- }
- ~WriteLocker(){
- if(_is_lock)
- _lock_point->Release();
- _is_lock = false;
- }
- void Lock(){
- if (!_is_lock)
- _lock_point->AcquireWrite();
- _is_lock = true;
- }
- void Unlock(){
- if (_is_lock)
- _lock_point->Release();
- _is_lock = false;
- }
- private:
- ThreadRWLock * _lock_point;
- bool _is_lock;
- };
- void fun(void){
- ThreadRWLock lock;
- WriteLocker writelock(lock); //自动获取写锁
- /*
- 临界区
- */
- //退出作用域自动释放写锁
- }
这篇关于c++实现的一对锁的封装(挺有意思的)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!