I have a situation where I would like to do something similar, as shown below, but there seems to be no way to query a mutex without changing its state. I don’t want it to someFunctionCalledRepeatedlyFromAnotherThread()hang, waiting for the mutex to free if it is locked. He should return immediately after performing some alternative actions. I assume that this omission exists for security, since the lock can be released during the time between the request and the return of the function. In my case, bad material will not happen if the lock is released, but it doSomeAlternativeAction()does. The fact that I am in this situation probably means that I am doing something wrong, so how do I change my design?
class MyClass
{
std::mutex initMutex;
public:
void someInitializationFunction()
{
std::lock_guard<std::mutex> lock(initMutex);
}
void someFunctionCalledRepeatedlyFromAnotherThread()
{
if (initMutex.isLocked())
{
doSomeAlternativeAction();
return;
}
std::lock_guard<std::mutex> lock(initMutex);
}
}