Tomáš Zato
Tomáš Zato

Reputation: 53319

Why does mutex try_lock return false even when you own the mutex?

Consider this simple code:

boost::mutex m;
m.lock();
bool locked = m.try_lock();
std::cout<< (!locked? "Can't use lock" : "Can use lock.")<<std::endl;
system("pause");

The code print's Can't use lock. This is a problem, because in my program, I need to perform an asynchronous operation only if the thread has exclusive rights to the lock. So:

  1. Why does try_lock return false when I own that mutex?
  2. How do I create a code block that is only executed by the thread that owns the lock?

Upvotes: 1

Views: 1415

Answers (1)

SergeyA
SergeyA

Reputation: 62613

Your code is badly design. Any attempt to use a recursive mutex is an indication of a design bug. In your code, you need to protect the resource you need, and should not matter for you if your thread currently owns resource or not.

Upvotes: -2

Related Questions