Skip to content

Commit

Permalink
Reinstate upgradeable read locks
Browse files Browse the repository at this point in the history
Based on a review comment, this reinstates the upgradeable read locks
that were originally taken before entering write locks.

The intent of this PR is to deprecate `Lock`, not to make functional
changes. While forgoing the upgradeable read locks in favor of enter-
ing write locks right away might *possibly* be an optimization, this
is a different concern and would need to be properly established using
careful benchmarking. Let's do this another time.
  • Loading branch information
stakx committed Jun 23, 2018
1 parent 3ebd4ba commit f6ea549
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ private bool TryGetExistingItem(TKey key, out object item)
locker.ExitReadLock();
}

locker.EnterWriteLock();
locker.EnterUpgradeableReadLock();
try
{
if (items.TryGetValue(key, out item))
Expand All @@ -74,13 +74,21 @@ private bool TryGetExistingItem(TKey key, out object item)
}
else
{
items[key] = item = new ManualResetEvent(false);
return false;
locker.EnterWriteLock();
try
{
items[key] = item = new ManualResetEvent(false);
return false;
}
finally
{
locker.ExitWriteLock();
}
}
}
finally
{
locker.ExitWriteLock();
locker.ExitUpgradeableReadLock();
}
}

Expand Down
23 changes: 20 additions & 3 deletions src/Castle.Core/Core/Internal/SynchronizedDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,31 @@ public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
itemsLock.ExitReadLock();
}

itemsLock.EnterWriteLock();
itemsLock.EnterUpgradeableReadLock();
try
{
return GetOrAddWithoutTakingLock(key, valueFactory);
if (items.TryGetValue(key, out value))
{
return value;
}
else
{
itemsLock.EnterWriteLock();
try
{
value = valueFactory.Invoke(key);
items.Add(key, value);
return value;
}
finally
{
itemsLock.ExitWriteLock();
}
}
}
finally
{
itemsLock.ExitWriteLock();
itemsLock.ExitUpgradeableReadLock();
}
}

Expand Down

0 comments on commit f6ea549

Please sign in to comment.