boost::unique_lock vs boost::lock_guard

前端 未结 5 1693
说谎
说谎 2020-12-12 14:06

I don\'t well understand the difference betweeen these two lock classes. In boost documentation it is said, boost::unique_lock doesn\'t realize lock automatical

5条回答
  •  忘掉有多难
    2020-12-12 14:27

    The currently best voted answer is good, but it did not clarify my doubt till I dug a bit deeper so decided to share with people who might be in the same boat.

    Firstly both lock_guard and unique_lock follows the RAII pattern, in the simplest use case the lock is acquired during construction and unlocked during destruction automatically. If that is your use case then you don't need the extra flexibility of unique_lock and lock_guard will be more efficient.

    The key difference between both is a unique_lock instance doesn't need to always own the mutex it is associated with while in lock_guard it owns the mutex. This means unique_lock would need to have an extra flag indicating whether it owns the lock and another extra method 'owns_lock()' to check that. Knowing this we can explain all extra benefits this flags brings with the overhead of that extra data to be set and checked

    1. 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.
    2. We can unlock it before the function ends and don't have to necessarily wait for destructor to release it, which can be handy.
    3. You can pass the ownership of the lock from a function, it is movable and not copyable.
    4. It can be used with conditional variables since that requires mutex to be locked, condition checked and unlocked while waiting for a condition.

提交回复
热议问题