Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between std::mutex lock function and std::lock_guard<std::mutex>?

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

  • 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.
like image 688
ashvardanian Avatar asked Jul 12 '16 23:07

ashvardanian


1 Answers

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 is an example of an RAII or SBRM type.

like image 80
Jonathan Wakely Avatar answered Sep 29 '22 20:09

Jonathan Wakely