1

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?
1

1 Answer 1

-2

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.

5
  • The problem is that the resource must be protected over asynchronous routine. That is, it can't happen in one function. Nov 4, 2015 at 17:06
  • Bad design. This way is a real fast way to deadlock. Every lock on the resource should have a predictable life span.
    – SergeyA
    Nov 4, 2015 at 17:12
  • Hello, just coming here to tell you that you were right, the design was bad. But still, your answer should rather be a comment, not answer. Nov 23, 2015 at 13:59
  • @TomášZato, I appreciate you telling me so, and I hope your new design suits you well. I also believe it is indeed an answer, as I hope it put your thoughts in the right direction. You know, when someone asks how to chop his head off, you might answer with the right technique, or might try to persuade him to do something else instead. I believe in the value of the latter.
    – SergeyA
    Nov 23, 2015 at 14:21
  • I would do the former - with appropriate warning - even if the situation was literally as you describe it. Because I, on the contrary, believe that questions should be answered, not bypassed. My opinion is reinforced by many answers of people who were so sure they should answer something else that was asked and they didn't think maybe someone else from google will have a reason to do what OP asked, even if OP shouldn't do it. Nov 23, 2015 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.