How do std::mutex, std::recursive_mutex, and std::shared_mutex differ, and when is each appropriate?
Show answer and explanation
std::mutex provides one non-recursive exclusive owner; calling lock again from the owning thread violates its precondition and has undefined behavior rather than providing recursion. std::recursive_mutex tracks repeated ownership by the same thread until matching unlocks occur, but it can hide unclear re-entrancy and invariant boundaries. std::shared_mutex permits either one exclusive writer or multiple shared readers, which helps only when reads dominate and the extra coordination cost pays off; the Standard does not promise a particular fairness policy. In every case, scope-bound lock wrappers should express ownership and the protected invariant must be documented.
std::mutex provides one non-recursive exclusive owner; calling lock again from the owning thread violates its precondition and has undefined behavior rather than providing recursion. std::recursive_mutex tracks repeated ownership by the same thread until matching unlocks occur, but it can hide unclear re-entrancy and invariant boundaries. std::shared_mutex permits either one exclusive writer or multiple shared readers, which helps only when reads dominate and the extra coordination cost pays off; the Standard does not promise a particular fairness policy. In every case, scope-bound lock wrappers should express ownership and the protected invariant must be documented.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.