Why use defer lock? What is with taking ownership first then locking? Isn't taking ownership and locking kinda same. What if we took ownership using unique lock of a mutex and not locking, could it still be prone to race conditions?
void fun1(std::mutex &m){
std::lock_guard<std::mutex> mlock(m);
//multiple lines
}
void fun2(std::mutex &m){
std::unique_lock<std::mutex,std::defer_lock> mlock(m);
//multiple lines
mlock.lock();
//multiple lines
}
This does not "take ownership" of the mutex
m:In effect, it says, I want to construct this RAII object,
mlocknow, but I am not going to lockm(i.e., "take ownership ofm") until later.Absolutely. Yes.
Response to comment, below
Only use case I can think of* is similar to what's shown on the cppreference web page to which @Mat referred you.
So, you write something like this:
* Maybe there's other uses. Just because *I* can't imagine something doesn't mean it's not out there waiting for somebody else to imagine it.