C++并發(fā)編程 - 互斥鎖
在多線程的編程中,共享數(shù)據(jù)的修改限制是必不可少的環(huán)節(jié)。期望的是:當(dāng)一個(gè)線程訪問共享數(shù)據(jù)期間靴患,此數(shù)據(jù)不應(yīng)該被其他線程修改桨菜;當(dāng)某個(gè)線程修改了共享數(shù)據(jù)豁状,應(yīng)通知其他線程捉偏。
例如,買車票場(chǎng)景: 座位為共享數(shù)據(jù)泻红,每個(gè)用戶屬于一個(gè)訪問共享數(shù)據(jù)的線程夭禽,當(dāng)一個(gè)用戶開始購買某個(gè)座位車票期間,該座位就應(yīng)該禁止被其他用戶購買谊路。從而避免同一個(gè)座位同時(shí)被兩個(gè)用戶買到讹躯。
通常情況下,解決類似并發(fā)問題缠劝,首先考慮舍棄并發(fā)潮梯;若迫不得已,互斥量(mutex)是一個(gè)很好選擇惨恭。
互斥鎖
互斥量
互斥鎖是依賴互斥量實(shí)現(xiàn)的秉馏。互斥量可簡單理解為僅有兩種值true或false的信號(hào)量脱羡。
互斥鎖
互斥鎖基于互斥量實(shí)現(xiàn)萝究,可用于共享數(shù)據(jù)訪問的保護(hù)。即當(dāng)線程訪問共享數(shù)據(jù)時(shí)锉罐,有如下動(dòng)作:
- 訪問前糊肤,判斷互斥鎖是否已上鎖(互斥量是否置為true)。若上鎖氓鄙,說明有其他線程再訪問馆揉,當(dāng)前線程阻塞直至互斥鎖解鎖;若未上鎖抖拦,當(dāng)前線程上鎖升酣,并訪問共享數(shù)據(jù)。
- 訪問后态罪,退出共享數(shù)據(jù)的訪問噩茄,并解鎖互斥鎖。
在Linux C中互斥鎖有pthread_mutex_t方法复颈,但是對(duì)于C++編程中绩聘,更推薦使用lock_guard、unqiue_lock耗啦。主要有以下優(yōu)勢(shì):
無需考慮互斥量的初始化和銷毀凿菩,在類的構(gòu)造和析構(gòu)函數(shù)中管理,無需使用者操心帜讲。
采用RAII對(duì)互斥量進(jìn)行了不同封裝衅谷,提供了更方便的上鎖機(jī)制。
對(duì)比pthread_mutex_t似将,功能都一樣获黔,只是使用上更加方便和靈活蚀苛。畢竟經(jīng)過c++大佬們深思熟慮設(shè)計(jì)出來的,如果沒有優(yōu)勢(shì)玷氏,也就不會(huì)發(fā)布出來堵未。
lock_guard
lock_guard功能與std::mutex的lock與ublock功能相同。 不同的是盏触,lock_guard析構(gòu)時(shí)會(huì)自動(dòng)解鎖渗蟹,使用時(shí)無須unlock。這就需要我們將共享資源的訪問封裝成盡可能小的函數(shù)耻陕,避免加鎖時(shí)間過長拙徽。
lock_guard類主要源碼
template<class _Mutex>
class lock_guard
{
public:
using mutex_type = _Mutex;
// construct and lock
explicit lock_guard(_Mutex& _Mtx)
: _MyMutex(_Mtx)
{
_MyMutex.lock();
}
// construct but don't lock
lock_guard(_Mutex& _Mtx, adopt_lock_t)
: _MyMutex(_Mtx)
{
}
// destructor and unlocks
~lock_guard() noexcept
{
_MyMutex.unlock();
}
lock_guard(const lock_guard&) = delete;
lock_guard& operator=(const lock_guard&) = delete;
private:
_Mutex& _MyMutex;
};
從構(gòu)造與析構(gòu)可以看出,lock_guard對(duì)象創(chuàng)建時(shí)會(huì)主動(dòng)調(diào)用lock()加鎖诗宣,銷毀時(shí)會(huì)主動(dòng)調(diào)用unlock()解鎖膘怕。
unique_lock
unique_lock比lock_guard更加靈活,但性能不如lock_guard召庞。unique_lock提供lock與unlock岛心,同時(shí)析構(gòu)時(shí)也會(huì)釋放鎖。
std::unique_lock 可以在構(gòu)造時(shí)傳遞第二個(gè)參數(shù)用于管理互斥量篮灼,且能傳遞不同域中互斥量所有權(quán)忘古。
unique_lock類主要源碼
template<class _Mutex>
class unique_lock
{ // whizzy class with destructor that unlocks mutex
public:
typedef unique_lock<_Mutex> _Myt;
typedef _Mutex mutex_type;
// CONSTRUCT, ASSIGN, AND DESTROY
unique_lock() _NOEXCEPT
: _Pmtx(0), _Owns(false)
{ // default construct
}
explicit unique_lock(_Mutex& _Mtx)
: _Pmtx(&_Mtx), _Owns(false)
{ // construct and lock
_Pmtx->lock();
_Owns = true;
}
unique_lock(_Mutex& _Mtx, adopt_lock_t)
: _Pmtx(&_Mtx), _Owns(true)
{ // construct and assume already locked
}
unique_lock(_Mutex& _Mtx, defer_lock_t) _NOEXCEPT
: _Pmtx(&_Mtx), _Owns(false)
{ // construct but don't lock
}
unique_lock(_Mutex& _Mtx, try_to_lock_t)
: _Pmtx(&_Mtx), _Owns(_Pmtx->try_lock())
{ // construct and try to lock
}
template<class _Rep,
class _Period>
unique_lock(_Mutex& _Mtx,
const chrono::duration<_Rep, _Period>& _Rel_time)
: _Pmtx(&_Mtx), _Owns(_Pmtx->try_lock_for(_Rel_time))
{ // construct and lock with timeout
}
template<class _Clock,
class _Duration>
unique_lock(_Mutex& _Mtx,
const chrono::time_point<_Clock, _Duration>& _Abs_time)
: _Pmtx(&_Mtx), _Owns(_Pmtx->try_lock_until(_Abs_time))
{ // construct and lock with timeout
}
unique_lock(_Mutex& _Mtx, const xtime *_Abs_time)
: _Pmtx(&_Mtx), _Owns(false)
{ // try to lock until _Abs_time
_Owns = _Pmtx->try_lock_until(_Abs_time);
}
unique_lock(unique_lock&& _Other) _NOEXCEPT
: _Pmtx(_Other._Pmtx), _Owns(_Other._Owns)
{ // destructive copy
_Other._Pmtx = 0;
_Other._Owns = false;
}
unique_lock& operator=(unique_lock&& _Other)
{ // destructive copy
if (this != &_Other)
{ // different, move contents
if (_Owns)
_Pmtx->unlock();
_Pmtx = _Other._Pmtx;
_Owns = _Other._Owns;
_Other._Pmtx = 0;
_Other._Owns = false;
}
return (*this);
}
~unique_lock() _NOEXCEPT
{ // clean up
if (_Owns)
_Pmtx->unlock();
}
unique_lock(const unique_lock&) = delete;
unique_lock& operator=(const unique_lock&) = delete;
// LOCK AND UNLOCK
void lock()
{ // lock the mutex
_Validate();
_Pmtx->lock();
_Owns = true;
}
bool try_lock()
{ // try to lock the mutex
_Validate();
_Owns = _Pmtx->try_lock();
return (_Owns);
}
template<class _Rep,
class _Period>
bool try_lock_for(const chrono::duration<_Rep, _Period>& _Rel_time)
{ // try to lock mutex for _Rel_time
_Validate();
_Owns = _Pmtx->try_lock_for(_Rel_time);
return (_Owns);
}
template<class _Clock,
class _Duration>
bool try_lock_until(
const chrono::time_point<_Clock, _Duration>& _Abs_time)
{ // try to lock mutex until _Abs_time
_Validate();
_Owns = _Pmtx->try_lock_until(_Abs_time);
return (_Owns);
}
bool try_lock_until(const xtime *_Abs_time)
{ // try to lock the mutex until _Abs_time
_Validate();
_Owns = _Pmtx->try_lock_until(_Abs_time);
return (_Owns);
}
void unlock()
{ // try to unlock the mutex
if (!_Pmtx || !_Owns)
_THROW_NCEE(system_error,
_STD make_error_code(errc::operation_not_permitted));
_Pmtx->unlock();
_Owns = false;
}
// MUTATE
void swap(unique_lock& _Other) _NOEXCEPT
{ // swap with _Other
_STD swap(_Pmtx, _Other._Pmtx);
_STD swap(_Owns, _Other._Owns);
}
_Mutex *release() _NOEXCEPT
{ // disconnect
_Mutex *_Res = _Pmtx;
_Pmtx = 0;
_Owns = false;
return (_Res);
}
// OBSERVE
bool owns_lock() const _NOEXCEPT
{ // return true if this object owns the lock
return (_Owns);
}
explicit operator bool() const _NOEXCEPT
{ // return true if this object owns the lock
return (_Owns);
}
_Mutex *mutex() const _NOEXCEPT
{ // return pointer to managed mutex
return (_Pmtx);
}
private:
_Mutex *_Pmtx;
bool _Owns;
void _Validate() const
{ // check if the mutex can be locked
if (!_Pmtx)
_THROW_NCEE(system_error,
_STD make_error_code(errc::operation_not_permitted));
if (_Owns)
_THROW_NCEE(system_error,
_STD make_error_code(errc::resource_deadlock_would_occur));
}
};
// SWAP
template<class _Mutex>
void swap(unique_lock<_Mutex>& _Left,
unique_lock<_Mutex>& _Right) _NOEXCEPT
{ // swap _Left and _Right
_Left.swap(_Right);
}
unique_lock私有成員為指針 _Mutex *_Pmtx
,指向傳遞進(jìn)來的互斥量诅诱,lock_guard私有成員為引用_Mutex& _MyMutex
髓堪,引用傳遞進(jìn)的互斥量。這就決定了unique_lock能夠?qū)崿F(xiàn)傳遞互斥量的功能娘荡。
另外通過觀察unique_lock幾種構(gòu)造干旁,不同的情況可使用對(duì)應(yīng)的構(gòu)造創(chuàng)建對(duì)象:
unique_lock(mutex)
傳遞未被使用的mutex,通過炮沐。會(huì)上鎖争群,無法獲得鎖時(shí)會(huì)阻塞。unique_lock(mutex, adopt_lock_t)
傳遞被使用過的mutex大年,且已經(jīng)被上過鎖换薄,通過。無上鎖動(dòng)作翔试,不阻塞轻要。unique_lock(mutex, defer_lock_t)
傳遞被使用過的mutex,未被上過鎖遏餐。無上鎖動(dòng)作伦腐,不阻塞。unique_lock(mutex, try_to_lock_t)
任何狀態(tài)的mutex失都。嘗試上鎖柏蘑,不阻塞。unique_lock(_Mutex& _Mtx, const chrono::duration<_Rep, _Period>& _Rel_time)
在指定時(shí)間長內(nèi)嘗試獲取傳遞的mutex的鎖返回粹庞。若無法獲取鎖咳焚,會(huì)阻塞到指定時(shí)間長。unique_lock(mutex_type& m,std::chrono::time_point<Clock,Duration> const& absolute_time)
在給定時(shí)間點(diǎn)嘗試獲取傳遞的mutex鎖返回庞溜。若無法獲取鎖革半,會(huì)阻塞到指定時(shí)間點(diǎn)。unique_lock(unique_lock&& _Other)
將已經(jīng)創(chuàng)建的unique_lock鎖的所有權(quán)轉(zhuǎn)移到新的鎖流码。保持之前鎖的狀態(tài)又官,不阻塞。
unique_lock的用法比較多漫试,如果對(duì)鎖的需求比較簡單推薦使用lock_guard六敬。當(dāng)需要超時(shí)或者手動(dòng)解鎖等功能,可以考慮使用unique_lock
總結(jié)
相對(duì)于Linux原生互斥鎖的API驾荣,C++封裝的lock_guard外构、unique_lock使用更方便和靈活。如果不是有執(zhí)念播掷,可以嘗試使用C++的接口审编。
lock_guard與unique_lock的差異主要在于對(duì)mutex的管理,其根本取決于兩者對(duì)于mutex的存儲(chǔ)方式不同歧匈。lock_guard通過內(nèi)部成員變量存儲(chǔ)mutex垒酬,故其無法操作原本的mutex。而unique_lock通過內(nèi)部指針指向mutex件炉,故其能夠操作和傳遞原本的mutex勘究。