boost::unique_lock vs boost::lock_guard

前端 未结 5 1688
说谎
说谎 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条回答
  •  萌比男神i
    2020-12-12 14:09

    First to answer your question. No you don't need to call lock on a unique_lock. See below:

    The unique_lock is only a lock class with more features. In most cases the lock_guard will do what you want and will be sufficient.
    The unique_lock has more features to offer to you. E.g a timed wait if you need a timeout or if you want to defer your lock to a later point than the construction of the object. So it highly depends on what you want to do. BTW: The following code snippets do the same thing.

    boost::mutex mutex;
    boost::lock_guard lock(mutex);
    

    boost::mutex mutex;
    boost::unique_lock lock(mutex);
    

    The first one can be used to synchronize access to data, but if you want to use condition variables you need to go for the second one.

提交回复
热议问题