本文主要是介绍RAII手法封装互斥锁,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
RAII手法 resource acquisition is initialization(资源获取就是初始化) 使用局部对象管理资源的技术通常称为“资源获取就是初始化”。这种通用技术依赖于构造函数和析构函数的性质以及它们与异常处理的交互作用。
模板方式
template <typename Mutex>
class LockGuard
{
public:explicit LockGuard(Mutex& m): m_(m){m_.Lock();}~LockGuard(){m_.Unlock();}private:LockGuard(const LockGuard&);LockGuard& operator=(const LockGuard&);Mutex& m_;
};
#include <stdio.h>
#include <pthread.h>class MutexLock
{
public:MutexLock(){pthread_mutex_init(&m_mutex, NULL);printf("MutexLock\n");}~MutexLock(){pthread_mutex_destroy(&m_mutex);printf("~MutexLock\n");}void lock(){pthread_mutex_lock(&m_mutex);printf("lock\n");}void unlock(){pthread_mutex_unlock(&m_mutex);printf("unlock\n");}pthread_mutex_t* getPthreadMutex(){return &m_mutex;}private:MutexLock(const MutexLock&);MutexLock& operator= (const MutexLock&);private:pthread_mutex_t m_mutex;
};class MutexLockGuard
{
public:explicit MutexLockGuard(MutexLock& mutex) : m_mutex(mutex){m_mutex.lock();}~MutexLockGuard(){m_mutex.unlock();}private:MutexLockGuard(const MutexLockGuard&);MutexLockGuard& operator= (const MutexLockGuard&);private:MutexLock &m_mutex;
};#define MutexLockGuard(x) \static_assert(false, "missing mutex guard var name")int main(void)
{MutexLock lock;MutexLockGuard lockGuard(lock);printf("hello, this is lock\n");return 0;
}
编译:g++ -lpthread mutex.c
运行结果:
MutexLock
lock
hello, this is lock
unlock
~MutexLock
这篇关于RAII手法封装互斥锁的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!