I was researching possible implementations for the std::lock
function and stumbled upon an implementation posted on the code review community.
Quoting the accepted answer (emphasis mine):
No this does not meet the definition of std::lock().
It (std::lock) guarantees that no matter what order you specify the locks in the parameter list you will not fall into a deadlock situation.
[...]
This also means that if a lock in the list is already locked it must be released so that the locks are acquired in the correct order.
I cannot find a conclusive answer whether or not the last statement is correct.
My question: is it allowed (i.e. defined behavior) to pass a locked resource, owned by the calling thread, as an argument to the standard std::lock
function?
std::mutex m1, m2;
m1.lock();
std::lock(m1, m2);
My gut feeling says this is actually not allowed. The function expects two or more Lockable objects and there is no way to check if a Lockable object is already locked by the current thread of execution. So it seems impossible to implement std::lock
that way.