boost::unique_lock vs boost::lock_guard

前端 未结 5 1678
说谎
说谎 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:33

    If you're used to pthreads(3):

    • boost::mutex = pthread_mutex_*
    • boost::unique_lock = pthread_rwlock_* used to obtain write/exclusive locks (i.e. pthread_rwlock_wrlock)
    • boost::shared_lock = pthread_rwlock_* used to obtain read/shared locks (i.e. pthread_rwlock_rdlock)

    Yes a boost::unique_lock and a boost::mutex function in similar ways, but a boost::mutex is generally a lighter weight mutex to acquire and release. That said, a shared_lock with the lock already acquired is faster (and allows for concurrency), but it's comparatively expensive to obtain a unique_lock.

    You have to look under the covers to see the implementation details, but that's the gist of the intended differences.


    Speaking of performance: here's a moderately useful comparison of latencies:

    http://www.eecs.berkeley.edu/%7Ercs/research/interactive_latency.html

    It would be nice if I/someone could benchmark the relative cost of the different pthread_* primitives, but last I looked, pthread_mutex_* was ~25us, whereas pthread_rwlock_* was ~20-100us depending on whether or not the read lock had been already acquired (~10us) or not (~20us) or writer (~100us). You'll have to benchmark to confirm current numbers and I'm sure it's very OS specific.

提交回复
热议问题