lock_guard
std::lock_guard使用起来比较简单,其在构造函数中对std::mutex变量进行锁定,在其析构函数中对std::mutex变量进行解锁,整个类没有对mutex进行解锁和加锁的对外接口,其源码如下:
|
|
使用方法如下:
|
|
unique_lock
unique_lock相比lock_guard,功能要多很多,其提供了对mutex的加锁(lock和try_lock)和解锁(unlock)操作,同时可以配合条件变量condition_variable使用:
|
|
unique_lock和lock_guard的区别
简单的说,unique_lock相对于lock_guard,会有更多特性。
unique_lock和lock_guard都遵循RAII。
unique_lock和lock_guard最大的不同是unique_lock不需要始终拥有关联的mutex,而lock_guard始终拥有mutex。这意味着unique_lock需要利用owns_lock()判断是否拥有mutex。另外,如果要结合使用条件变量,应该使用unique_lock。
Lock doesn’t have to taken right at the construction, you can pass the flag std::defer_lock during its construction to keep the mutex unlocked during construction.
We can unlock it before the function ends and don’t have to necessarily wait for destructor to release it, which can be handy.
You can pass the ownership of the lock from a function, it is movable and not copyable.
It can be used with conditional variables since that requires mutex to be locked, condition checked and unlocked while waiting for a condition.
参考[StackOverflow]:https://stackoverflow.com/questions/6731027/boostunique-lock-vs-boostlock-guard
#使用建议和说明
如果只是在某个区间进行简单的对象互斥访问的话,建议使用unique_gurad,这个比unique_lock来的更高效;如果在操作过程中涉及对锁对象的解锁和加锁操作的话,或者是使用了条件变量的情况下,使用uique_lock才能满足你的要求。