boost::lock_guard vs boost::mutex::scoped_lock

孤街醉人 提交于 2019-11-29 10:37:35

问题


Which is preferred boost::lock_guard or boost::mutex::scoped_lock?

I'm using Boost.Thread with the hope to move to C++11 threading when it becomes available.

Is scoped_lock part of the next c++ standard?

Are the any advantages to prefer one over the other?


NOTE: I'm aware that scoped_lock is just a typedef of lock_guard.


edit: I was wrong scoped_lock is not a typedef of lock_guard. It's a typedef of unique_lock.


回答1:


Amit is right: boost::mutex::scoped_lock is a typedef for boost::unique_lock<boost::mutex>, not lock_guard. scoped_lock is not available in C++0x.

Unless you need the flexibility of unique_lock, I would use lock_guard. It is simpler, and more clearly expresses the intent to limit the lock to a defined scope.




回答2:


Not much difference between the two. As per Boost, scoped_lock is a typedef for unique_lock<mutex>. Both of unique_lock and lock_guard implement RAII-style locking. The difference between is simply that unique_lock has a more complex interface -- it allows to defer lock and call unlock.



来源:https://stackoverflow.com/questions/2276805/boostlock-guard-vs-boostmutexscoped-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!