Skip to content

Use consistent locking for async and sync code #2147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Apr 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions src/AsyncGenerator.yml
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,6 @@
transformation:
configureAwaitArgument: false
localFunctions: true
asyncLock:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will most likely remove this option in the future as adding an additional field for async locking allows two threads to execute the "same code" simultaneously.

type: NHibernate.Util.AsyncLock
methodName: LockAsync
documentationComments:
addOrReplaceMethodSummary:
- name: Commit
Expand Down
215 changes: 215 additions & 0 deletions src/NHibernate.Test/Async/UtilityTest/AsyncReaderWriterLockFixture.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by AsyncGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NHibernate.Util;
using NUnit.Framework;

namespace NHibernate.Test.UtilityTest
{
public partial class AsyncReaderWriterLockFixture
{

[Test, Explicit]
public async Task TestConcurrentReadWriteAsync()
{
var l = new AsyncReaderWriterLock();
for (var i = 0; i < 2; i++)
{
var writeReleaser = await (l.WriteLockAsync());
Assert.That(l.Writing, Is.True);

var secondWriteSemaphore = new SemaphoreSlim(0);
var secondWriteReleaser = default(AsyncReaderWriterLock.Releaser);
var secondWriteThread = new Thread(
() =>
{
secondWriteSemaphore.Wait();
secondWriteReleaser = l.WriteLock();
});
secondWriteThread.Priority = ThreadPriority.Highest;
secondWriteThread.Start();
await (AssertEqualValueAsync(() => secondWriteThread.ThreadState == ThreadState.WaitSleepJoin, true));

var secondReadThreads = new Thread[20];
var secondReadReleasers = new AsyncReaderWriterLock.Releaser[secondReadThreads.Length];
var secondReadSemaphore = new SemaphoreSlim(0);
for (var j = 0; j < secondReadReleasers.Length; j++)
{
var index = j;
var thread = new Thread(
() =>
{
secondReadSemaphore.Wait();
secondReadReleasers[index] = l.ReadLock();
});
thread.Priority = ThreadPriority.Highest;
secondReadThreads[j] = thread;
thread.Start();
}

await (AssertEqualValueAsync(() => secondReadThreads.All(o => o.ThreadState == ThreadState.WaitSleepJoin), true));

var firstReadReleaserTasks = new Task[30];
var firstReadStopSemaphore = new SemaphoreSlim(0);
for (var j = 0; j < firstReadReleaserTasks.Length; j++)
{
firstReadReleaserTasks[j] = Task.Run(async () =>
{
var releaser = await (l.ReadLockAsync());
await (firstReadStopSemaphore.WaitAsync());
releaser.Dispose();
});
}

await (AssertEqualValueAsync(() => l.ReadersWaiting, firstReadReleaserTasks.Length, waitDelay: 60000));

writeReleaser.Dispose();
secondWriteSemaphore.Release();
secondReadSemaphore.Release(secondReadThreads.Length);
await (Task.Delay(1000));
firstReadStopSemaphore.Release(firstReadReleaserTasks.Length);

await (AssertEqualValueAsync(() => firstReadReleaserTasks.All(o => o.IsCompleted), true));
Assert.That(l.ReadersWaiting, Is.EqualTo(secondReadThreads.Length));
Assert.That(l.CurrentReaders, Is.EqualTo(0));
await (AssertEqualValueAsync(() => secondWriteThread.IsAlive, false));
await (AssertEqualValueAsync(() => secondReadThreads.All(o => o.IsAlive), true));

secondWriteReleaser.Dispose();
await (AssertEqualValueAsync(() => secondReadThreads.All(o => !o.IsAlive), true));

Assert.That(l.ReadersWaiting, Is.EqualTo(0));
Assert.That(l.CurrentReaders, Is.EqualTo(secondReadThreads.Length));

foreach (var secondReadReleaser in secondReadReleasers)
{
secondReadReleaser.Dispose();
}

Assert.That(l.ReadersWaiting, Is.EqualTo(0));
Assert.That(l.CurrentReaders, Is.EqualTo(0));
}
}

[Test]
public async Task TestInvaildExitReadLockUsageAsync()
{
var l = new AsyncReaderWriterLock();
var readReleaser = await (l.ReadLockAsync());
var readReleaser2 = await (l.ReadLockAsync());

readReleaser.Dispose();
readReleaser2.Dispose();
Assert.Throws<InvalidOperationException>(() => readReleaser.Dispose());
Assert.Throws<InvalidOperationException>(() => readReleaser2.Dispose());
}

[Test]
public void TestOperationAfterDisposeAsync()
{
var l = new AsyncReaderWriterLock();
l.Dispose();

Assert.ThrowsAsync<ObjectDisposedException>(() => l.ReadLockAsync());
Assert.ThrowsAsync<ObjectDisposedException>(() => l.WriteLockAsync());
}

[Test]
public async Task TestInvaildExitWriteLockUsageAsync()
{
var l = new AsyncReaderWriterLock();
var writeReleaser = await (l.WriteLockAsync());

writeReleaser.Dispose();
Assert.Throws<InvalidOperationException>(() => writeReleaser.Dispose());
}

private static async Task LockAsync(
AsyncReaderWriterLock readWriteLock,
Random random,
LockStatistics lockStatistics,
System.Action checkLockAction,
Func<bool> canContinue, CancellationToken cancellationToken = default(CancellationToken))
{
while (canContinue())
{
var isRead = random.Next(100) < 80;
var releaser = isRead ? await (readWriteLock.ReadLockAsync()) : await (readWriteLock.WriteLockAsync());
lock (readWriteLock)
{
if (isRead)
{
lockStatistics.ReadLockCount++;
}
else
{
lockStatistics.WriteLockCount++;
}

checkLockAction();
}

await (Task.Delay(10, cancellationToken));

lock (readWriteLock)
{
releaser.Dispose();
if (isRead)
{
lockStatistics.ReadLockCount--;
}
else
{
lockStatistics.WriteLockCount--;
}

checkLockAction();
}
}
}

private static async Task AssertEqualValueAsync<T>(Func<T> getValueFunc, T value, Task task = null, int waitDelay = 5000, CancellationToken cancellationToken = default(CancellationToken))
{
var currentTime = 0;
var step = 5;
while (currentTime < waitDelay)
{
if (task != null)
{
task.Wait(step);
}
else
{
await (Task.Delay(step, cancellationToken));
}

currentTime += step;
if (getValueFunc().Equals(value))
{
return;
}

step *= 2;
}

Assert.That(getValueFunc(), Is.EqualTo(value));
}

private static Task AssertTaskCompletedAsync(Task task, CancellationToken cancellationToken = default(CancellationToken))
{
return AssertEqualValueAsync(() => task.IsCompleted, true, task, cancellationToken: cancellationToken);
}
}
}
5 changes: 5 additions & 0 deletions src/NHibernate.Test/NHibernate.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@
<Compile Remove="**\NHSpecificTest\NH2188\**" />
<Compile Remove="**\NHSpecificTest\NH3121\**" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\NHibernate\Util\AsyncReaderWriterLock.cs">
<Link>UtilityTest\AsyncReaderWriterLock.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<PackageReference Include="log4net" Version="2.0.8" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="1.0.19269.1" />
Expand Down
Loading