Bootstrap

线程同步-互斥锁和lock_guard 源码

/*这是一个简单的C++单例模式对mutex和lock_guard的使用代码*/
LOCK_GUARD(x) std::lock_gurad(decltype(x)) lk(x)
static mutex* m_pMutex;
static Singleton* Singleton::getInstance() {
		if (m_pInstance == nullptr) {
			LOCK_GUARD(x);
			if (m_pInstance == nullptr) {
				m_pInstance = new Singleton();
			}
		}
		return m_pInstance;
	}

lock_guard实现对锁的管理

/*
	*lock_guard C++源码 内容也比较简单
	*私有化了拷贝构造和赋值拷贝
	*在内部对锁和构造和析构进行了适配
*/
template<class _Mutex>
	class lock_guard<_Mutex>
	{	// specialization for a single mutex
public:
	typedef _Mutex mutex_type;

	explicit lock_guard(_Mutex& _Mtx)
		: _MyMutex(_Mtx)
		{	// construct and lock
		_MyMutex.lock();
		}

	lock_guard(_Mutex& _Mtx, adopt_lock_t)
		: _MyMutex(_Mtx)
		{	// construct but don't lock
		}

	~lock_guard() _NOEXCEPT
		{	// unlock
		_MyMutex.unlock();
		}

	lock_guard(const lock_guard&) = delete;
	lock_guard& operator=(const lock_guard&) = delete;
private:
	_Mutex& _MyMutex;
};

使用作用域实现对锁的范围管理;

;