views:

23

answers:

2

when a thread1 already acquired a lock on mutex object, if thread2 tries to acquire a lock on the same mutex object, thread2 will be blocked. here are my questions: 1. how will thread2 come to know that mutex object is unlocked? 2. will thread2 try to acquire lock at predifined intervals of time?

A: 

This is really OS dependant, but what usually happens is that thread2 gets suspended and put on a wait list maintained by the mutex. When the mutex becomes available, a thread on the mutex's waitlist gets removed from the list and put back on the list of active threads. The OS can then schedule it like it usually would. thread2 is totally quiescent until it can acquire the mutex.

mschaef
@allthank u guys
lakshman
A: 

I sense a misunderstanding of how a mutex works. When thread 2 tries to acquire a mutex that is already owned by thread 1, the call that tries to take the mutex will not return until the mutex becomes available (unless you have a timeout with trylock() variant).

So thread 2 does not need to loop there and keep trying to take the mutex (unless you're using a timeout so you can abort trying to take the mutex based on some other condition like a cancel condition).

Amardeep
My interpretation is that the OP was asking about the implementation of the mutex itself.
mschaef
@mschaef: Quite possibly you are correct. It is hard to tell OP's level of understanding based on the wording of the question.
Amardeep