std :: mutex锁定功能和std :: lock_guard< std :: mutex>之间的区别?

问题描述:

基本上,标题是不言自明的. 我通过以下方式使用它:

Basically, the title is self-explanatory. I use it in following way:

  • 代码在Objective-C ++中.
  • Objective-C类对不同目的的函数进行并发调用.
  • 由于C ++ std容器不是线程安全的,因此我在整个类中使用std::mutexlockunlock std::vector<T>编辑选项.
  • The code is in Objective-C++.
  • Objective-C classes make concurrent calls to different purpose functions.
  • I use std::mutex to lock and unlock std::vector<T> editing option across entire class, as C++ std containers are not thread safe.

lock_guard超出范围时,使用lock_guard会自动将其解锁.这样就不可能忘记在返回或引发异常时将其解锁.您应该始终更喜欢使用lock_guardunique_lock而不是使用mutex::lock().参见 http://kayari.org/cxx/antipatterns.html#locking-mutex

Using lock_guard automatically unlocks the mutex again when it goes out of scope. That makes it impossible to forget to unlock it, when returning, or when an exception is thrown. You should always prefer to use lock_guard or unique_lock instead of using mutex::lock(). See http://kayari.org/cxx/antipatterns.html#locking-mutex

lock_guard RAII 查看更多