-
Notifications
You must be signed in to change notification settings - Fork 0
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
artemiipatov
wants to merge
9
commits into
main
Choose a base branch
from
Lazy
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Lazy #2
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c5fb56e
Initial commit
artemiipatov dc68035
Refactoring
artemiipatov f32c4ca
Refactor
artemiipatov 2a30ac6
Refactor
artemiipatov 792ba6d
Refactor
artemiipatov 8bb25c5
fix Get() in concurrent lazy
artemiipatov c49c19c
migrate to .NET 7.0
artemiipatov 049d3fc
refactor; update ci
artemiipatov 17e96f1
make iscalculated field volatile
artemiipatov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
namespace Lazy; | ||
|
||
/// <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(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Стоило заглушить предупреждения или реально добавить хедер с лицензией