问题
Reading on locks in C#. I see that being able to acquire lock on same object multiple times is said to be possible because Monitors are re-entrant. The definition of re-entrant code as defined in wikipedia does not seem to fit well in this context. Can you please help me understand what is re-entrancy in the context of C# and how does it apply to Monitors? From what I have understood, when a thread has acquired a lock, it would not relinquish the lock when in the middle of a critical section - even if it yields CPU..as a result of which, no other thread would be able to acquire the monitor..where does re-entrancy come into picture?
回答1:
@Zbynek Vyskovsky - kvr000 has already explained what reentrancy means with regards to Monitor
.
Wikipedia defines "reentrant mutex" (recursive lock) as:
particular type of mutual exclusion (mutex) device that may be locked multiple times by the same process/thread, without causing a deadlock.
Here's a little example to help you visualise the concept:
void MonitorReentrancy()
{
var obj = new object();
lock (obj)
{
// Lock obtained. Must exit once to release.
// No *other* thread can obtain a lock on obj
// until this (outermost) "lock" scope completes.
lock (obj) // Deadlock?
{
// Nope, we've just *re-entered* the lock.
// Must exit twice to release.
bool lockTaken = false;
try
{
Monitor.Enter(obj, ref lockTaken); // Deadlock?
// Nope, we've *re-entered* lock again.
// Must exit three times to release.
}
finally
{
if (lockTaken) {
Monitor.Exit(obj);
}
// Must exit twice to release.
}
}
// Must exit once to release.
}
// At this point we have finally truly released
// the lock allowing other threads to obtain it.
}
回答2:
Reentrancy has many meanings actually.
Here in this context it means that the monitor can be entered by the same thread repeatedly several times and will unlock it once the same number of releases are done.
来源:https://stackoverflow.com/questions/34627144/monitors-and-re-entrancy-clarifies-difference-between-re-entrant-code-and-re-en