lundi 2 mars 2015

Ensuring that current thread holds a lock on a C++11 mutex

Is there a way to tell whether or not the current thread in C++11 holds a lock on a mutex? In particular I want to ensure that certain functions in a class are only called while the calling thread holds onto a lock (via std::lock_guard, std::unique_lock, or something similar) for the object, with the std::mutex being a member variable.


To avoid repeated locking and unlocking while the object is being used extensively, the responsibility for locking the mutex needs to be up to the caller, and cannot be in each individual function, and if the current thread does not have a lock on the mutex when any of these functions are called, I want to throw an exception.


It seems that I can't just use std::try_lock followed by an unlock as necessary because std::try_lock's behavior is undefined if the current thread already holds the lock.


Aucun commentaire:

Enregistrer un commentaire