Skip to content
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

Lazy #2

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-dotnet@v1
with:
dotnet-version: '6.x'
dotnet-version: '7.x'
- name: Build
run: for dir in */; do cd $dir; for sln in *.sln; do dotnet build $sln; cd ..; done; done
shell: bash
Expand Down
22 changes: 22 additions & 0 deletions Lazy/Lazy.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lazy", "Lazy\Lazy.csproj", "{93659D18-057E-4FF2-B8C4-25D891741798}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LazyTests", "LazyTests\LazyTests.csproj", "{11D67AE1-D6D2-4898-AA5E-79E50A9737CA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{93659D18-057E-4FF2-B8C4-25D891741798}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{93659D18-057E-4FF2-B8C4-25D891741798}.Debug|Any CPU.Build.0 = Debug|Any CPU
{93659D18-057E-4FF2-B8C4-25D891741798}.Release|Any CPU.ActiveCfg = Release|Any CPU
{93659D18-057E-4FF2-B8C4-25D891741798}.Release|Any CPU.Build.0 = Release|Any CPU
{11D67AE1-D6D2-4898-AA5E-79E50A9737CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{11D67AE1-D6D2-4898-AA5E-79E50A9737CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{11D67AE1-D6D2-4898-AA5E-79E50A9737CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{11D67AE1-D6D2-4898-AA5E-79E50A9737CA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
14 changes: 14 additions & 0 deletions Lazy/Lazy/ILazy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace Lazy;

Choose a reason for hiding this comment

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

Стоило заглушить предупреждения или реально добавить хедер с лицензией


/// <summary>
/// Defers the execution of given function. Function executes only once and only when Get() is called.
/// </summary>
/// <typeparam name="T">Return type of a function.</typeparam>
public interface ILazy<T>
{
/// <summary>
/// Executes function and return the result if Get() is called for the first time. If Get() is called not for the first time, it just returns the result of the first execution.
/// </summary>
/// <returns>The result of the first function execution.</returns>
T? Get();
}
17 changes: 17 additions & 0 deletions Lazy/Lazy/Lazy.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>11</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

</Project>
48 changes: 48 additions & 0 deletions Lazy/Lazy/LazyConcurrent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
namespace Lazy;

/// <summary>
/// Lazy that can be used safely by multiple threads. It guarantees that there won't be any deadlocks or races.
/// </summary>
/// <typeparam name="TResult">Return type of a function.</typeparam>
public class LazyConcurrent<TResult> : ILazy<TResult>
{
private readonly object _locker = new();

private volatile bool _isCalculated;

private Func<TResult?>? _func;

private TResult? _result;

/// <summary>
/// Initializes a new instance of the <see cref="LazyConcurrent{T}"/> class.
/// </summary>
/// <param name="func">The delegate to be executed lazily.</param>
public LazyConcurrent(Func<TResult?> func)
{
_func = func;
}

/// <inheritdoc/>
public TResult? Get()
{
if (_isCalculated)
{
return _result;
}

lock (_locker)

Choose a reason for hiding this comment

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

Не-а, так lock будет браться при каждом обращении к методу, тогда как гонка тут возможна только при первом обращении, когда _result ещё не инициализирован. Такой способ убивает всю параллельность

{
if (_isCalculated)
{
return _result;
}

_result = _func!(); // It cannot be null because argument is not nullable.
_func = null;
_isCalculated = true;

return _result;
}
}
}
37 changes: 37 additions & 0 deletions Lazy/Lazy/LazySerial.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
namespace Lazy;

/// <summary>
/// Lazy that does not support multithreading.
/// </summary>
/// <typeparam name="T">Return type of a function.</typeparam>
public class LazySerial<T> : ILazy<T>
{
private Func<T?>? _func;

private bool _isCalculated;

private T? _result;

/// <summary>
/// Initializes a new instance of the <see cref="LazySerial{T}"/> class.
/// </summary>
/// <param name="func">The delegate to be executed lazily.</param>
public LazySerial(Func<T?> func)
{
_func = func;
}

/// <inheritdoc/>
public T? Get()
{
if (_isCalculated)
{
return _result;
}

_result = _func!(); // It cannot be null because argument is not nullable.
_func = null;
_isCalculated = true;
return _result;
}
}
102 changes: 102 additions & 0 deletions Lazy/LazyTests/LazyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
namespace LazyTest;

using System.Threading;
using Lazy;
using NUnit.Framework;

public class LazyTests
{
[Test]
public void SerialLazyExecutesFunctionOnlyOnce()
{
var counter = 0;
ILazy<int> lazy = new LazySerial<int>(() => ++counter);
for (var i = 0; i < 10; i++)
{
Assert.AreEqual(1, lazy.Get());
}

Assert.AreEqual(1, counter);
}

[Test]
public void ConcurrentLazyExecutesFunctionOnlyOnce()
{
var counter = 0;
var threads = new Thread[1000];
ILazy<int> lazy = new LazyConcurrent<int>(() => Interlocked.Increment(ref counter));

for (var i = 0; i < 1000; i++)
{
threads[i] = new Thread(() =>
{
for (var _ = 0; _ < 1000; _++)
{
Assert.AreEqual(1, lazy.Get());
}
});
}

foreach (var thread in threads)
{
thread.Start();
}

foreach (var thread in threads)
{
thread.Join();
}

Assert.AreEqual(1, counter);
}

[Test]
public void LaziesCanReturnNull()
{
ILazy<object> lazySerial = new LazySerial<object>(() => null);
ILazy<object> lazyConcurrent = new LazyConcurrent<object>(() => null);

for (var i = 0; i < 5; i++)
{
Assert.IsNull(lazySerial.Get());
Assert.IsNull(lazyConcurrent.Get());
}
}

[Test]
public void MultithreadingDoesNotCauseRaceCondition()
{
var counter = 0;
var threads = new Thread[1000];
ILazy<int> lazy = new LazyConcurrent<int>(() =>
{
for (var j = 0; j < 1000; j++)
{
Interlocked.Increment(ref counter);
}

return counter;
});

for (var i = 0; i < 1000; i++)
{
threads[i] = new Thread(() =>
{
for (var _ = 0; _ < 1000; _++)
{
Assert.AreEqual(1000, lazy.Get());
}
});
}

foreach (var thread in threads)
{
thread.Start();
}

foreach (var thread in threads)
{
thread.Join();
}
}
}
29 changes: 29 additions & 0 deletions Lazy/LazyTests/LazyTests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>

<RootNamespace>LazyTest</RootNamespace>

<LangVersion>11</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="NUnit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
<PackageReference Include="coverlet.collector" Version="3.1.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Lazy\Lazy.csproj" />
</ItemGroup>

</Project>