0

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;
}
Community
  • 1
  • 1
  • Are you looking for `mutex::try_lock()`, or perhaps `unique_lock::try_lock()`? As you correctly surmise, `unique_lock` is not designed to be shared between threads. – Igor Tandetnik Feb 10 '16 at 19:22
  • When writing multi threaded code I like to be able to put asserts in my code that confirms that you hold a required lock. I was hoping that there was something available in stl that would allow me to do it but it does not look like there is anything. I wrote a simple class that wraps around std::mutex that in debug builds only keeps track of the owning thread id. – Paul Beerkens Apr 05 '16 at 13:55
  • I ended up using the suggestion from Ami Tavory in [this page](http://stackoverflow.com/questions/21892934/how-to-assert-if-a-stdmutex-is-locked). It is working really well. – Paul Beerkens Apr 05 '16 at 14:00

0 Answers0