The std::lock_guard
is only used for two purposes:
- Automate mutex unlock during destruction (no need to call
.unlock()
).
- Allow simultaneous lock of multiple mutexes to overcome deadlock problem.
For the last use case you will need std::adopt_lock
flag:
std::lock(mutex_one, mutex_two);
std::lock_guard<std::mutex> lockPurposeOne(mutex_one, std::adopt_lock);
std::lock_guard<std::mutex> lockPurposeTwo(mutex_two, std::adopt_lock);
On the other hand, you will need allocate yet another class instance for the guard every time you need to lock the mutex, as std::lock_guard
has no member functions. If you need guard with unlocking functionality take a look at std::unique_lock
class. You may also consider using std::shared_lock
for parallel reading of your vector.
You may notice, that std::shared_lock
class is commented in header files and will be only accessible with C++17. According to header file you can use std::shared_timed_mutex
, but when you will try to build the app it will fail, as Apple had updated the header files, but not the libc++ itself.
So for Objective-C app it may be more convenient to use GCD, allocate a couple of queue for all your C++ containers at the same time and put semaphores where needed. Take a look at this excellent comparison.