Tip 41

As we know the code that accesses a common resource when enclosed within Monitor.Enter( ) and Monitor.Exit( ) helps in synchronizing concurrently running threads. What if one thread calls Monitor.Enter( ) twice. Will it go into the wait state since lock has already been acquired? The answer is no. This is because Enter( ) always checks which thread has acquired the resource before making the thread wait. Initially when resource is not acquired, count in the syncblock is set to zeros. When Enter( ) is called for the first time count becomes 1. If Enter( ) is called again and it finds that the same thread has acquired the resource it just increments the count without making the thread wait. This behavior seems logical otherwise the thread would have gone into indefinite wait state expecting from itself to release the resource. The Exit( ) method then decrements the count. When the Exit( ) method finds that the count has reached zero, it releases the lock and makes the waiting thread as the ready thread.

Subscribe / Share

It's very calm over here, why not leave a comment?

Leave a Reply




Categories

Powered by Yahoo! Answers