I am trying to use the advise found here: How to assert if a std::mutex is locked? to check if a mutex is currently locked. It seems to work at a first glance but it crashed when you try to use it from multiple threads. My guess is that unique_lock is not thread safe which would make a lot of sense which would mean there is no easy way to check if a mutex is already locked without writing a wrapper.
#include <iostream>
#include <thread>
#include <mutex>
long glob=0;
std::mutex mutex_;
std::unique_lock <std::mutex> glock (mutex_, std::defer_lock);
void call_from_thread (int tid)
{
std::cout <<"Started "<<tid<<std::endl;
for (int i=0; i<1000; ++i)
{
std::lock_guard< std::unique_lock <std::mutex> > lock2 (glock);
std::cout<<tid<<":"<<i<<":"<<glob<<std::endl;
++glob;
};
std::cout<<"Done "<<tid<<std::endl;
};
int main ()
{
std::thread t [10];
for (int i=0; i<10; ++i)
{
t[i]=std::thread (call_from_thread, i);
};
for (int i=0; i<10; ++i)
{
t[i].join ();
};
std::cout <<"Glob = "<<glob<<std::endl;
return 0;
}