Detect Boost recursive_mutex already acquired

I have a multi-threading problem where multiple threads access a function protected by a recursive_mutex.

When one thread has acquired the lock, I'd like other threads to simply exit and try later.  My problem is that I don't know how to determine that the mutex has already been acquired.

Here is a simple sample Windows program:

#include <windows.h>
#include <iostream>
#include <boost/thread/thread.hpp>
#include "boost/thread/recursive_mutex.hpp"

boost::recursive_mutex singleThreaded;

void ThreadProc() {
   // Want to exit if the mutex has already been acquired
   // What do I do?
   boost::recursive_mutex::scoped_lock scoped_lock(singleThreaded);
   std::cout << "Acquired the mutex" << std::endl;
   ::Sleep(500);
   std::cout << "Exit" << std::endl;
}

void main() {
   boost::thread one(&ThreadProc);
   boost::thread two(&ThreadProc);
   one.join();
   two.join();
}
LVL 13
josgoodAsked:
Who is Participating?
 
josgoodAuthor Commented:
Thank you, jkr.  That works like a charm.

#include <windows.h>
#include <iostream>
#include <boost/thread/thread.hpp>
#include "boost/thread/recursive_mutex.hpp"

boost::recursive_try_mutex singleThreaded;

void ThreadProc() {
   boost::recursive_try_mutex::scoped_try_lock scoped_lock(singleThreaded);
   if (scoped_lock.locked()) {
      std::cout << "Acquired the mutex" << std::endl;
      ::Sleep(500);
   } else {
      std::cout << "Mutex has already been acquired" << std::endl;
   }
   std::cout << "Exit" << std::endl;
}

void main() {
   boost::thread one(&ThreadProc);
   boost::thread two(&ThreadProc);
   one.join();
   two.join();
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.