-
Notifications
You must be signed in to change notification settings - Fork 0
Lazyy #2
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
Open
MikePuzanov
wants to merge
9
commits into
master
Choose a base branch
from
Lazyy
base: master
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
Lazyy #2
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c375b32
add needs class and interface
lykwer cae4051
add some tests
lykwer c368a97
add comments
lykwer ea0fe95
fix code
lykwer 583ef8b
fix code
lykwer 3178cf3
fix
lykwer daed898
fix
lykwer 1fe5b98
fix test
lykwer a833011
rename file
lykwer 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 hidden or 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,69 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Threading; | ||
| using NUnit.Framework; | ||
|
|
||
| namespace Lazyy.Test | ||
| { | ||
| public class SingleThreadTest | ||
| { | ||
| private static IEnumerable<TestCaseData> Lazy() | ||
| { | ||
| int countForSingle = 0; | ||
| int countForMulti = 0; | ||
| yield return new TestCaseData(LazyFactory.CreateSingleLazy(() => ++countForSingle)); | ||
| yield return new TestCaseData(LazyFactory.CreateMultiLazy(() => Interlocked.Increment(ref countForMulti))); | ||
| } | ||
|
|
||
| [Test] | ||
| public void SupplierCannotBeNull() | ||
| { | ||
| Assert.Throws<ArgumentNullException>(() => LazyFactory.CreateSingleLazy<int>(null)); | ||
| Assert.Throws<ArgumentNullException>(() => LazyFactory.CreateMultiLazy<int>(null)); | ||
| } | ||
|
|
||
| [TestCaseSource(nameof(Lazy))] | ||
| public void TestLazyLaunchFunctionOnly1Time<T>(ILazy<T> lazy) | ||
| { | ||
| for (int i = 0; i < 100; i++) | ||
| { | ||
| Assert.AreEqual(1, lazy.Get()); | ||
| } | ||
| } | ||
|
|
||
| [TestCaseSource(nameof(Lazy))] | ||
| public void GetShouldNotChangeValue<T>(ILazy<T> lazy) | ||
| { | ||
| var value = lazy.Get(); | ||
| Assert.AreEqual(1, value); | ||
| for (int i = 0; i < 25; i++) | ||
| { | ||
| Assert.AreEqual(value, lazy.Get()); | ||
| } | ||
| } | ||
|
|
||
| [Test] | ||
| public void RaceConditionsCheck() | ||
| { | ||
| var count = 0; | ||
| var lazy = LazyFactory.CreateMultiLazy(() => Interlocked.Increment(ref count)); | ||
| var threads = new Thread[10]; | ||
|
|
||
| for (int i = 0; i < threads.Length; ++i) | ||
| { | ||
| threads[i] = new Thread(() => lazy.Get()); | ||
| } | ||
|
|
||
| foreach (var thread in threads) | ||
| { | ||
| thread.Start(); | ||
| } | ||
| foreach (var thread in threads) | ||
| { | ||
| thread.Join(); | ||
| } | ||
|
|
||
| Assert.AreEqual(1, count); | ||
| } | ||
| } | ||
| } |
This file contains hidden or 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,20 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net5.0</TargetFramework> | ||
|
|
||
| <IsPackable>false</IsPackable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" /> | ||
| <PackageReference Include="NUnit" Version="3.13.1" /> | ||
| <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> | ||
| <PackageReference Include="coverlet.collector" Version="3.0.2" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Lazyy\Lazyy.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or 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}") = "Lazyy", "Lazyy\Lazyy.csproj", "{DB81654E-7FB5-4DF1-BEB0-8E701E1A3A6A}" | ||
| EndProject | ||
| Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lazyy.Test", "Lazyy.Test\Lazyy.Test.csproj", "{96805220-7A8C-4502-9503-91EB73541008}" | ||
| EndProject | ||
| Global | ||
| GlobalSection(SolutionConfigurationPlatforms) = preSolution | ||
| Debug|Any CPU = Debug|Any CPU | ||
| Release|Any CPU = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(ProjectConfigurationPlatforms) = postSolution | ||
| {DB81654E-7FB5-4DF1-BEB0-8E701E1A3A6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
| {DB81654E-7FB5-4DF1-BEB0-8E701E1A3A6A}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
| {DB81654E-7FB5-4DF1-BEB0-8E701E1A3A6A}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
| {DB81654E-7FB5-4DF1-BEB0-8E701E1A3A6A}.Release|Any CPU.Build.0 = Release|Any CPU | ||
| {96805220-7A8C-4502-9503-91EB73541008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
| {96805220-7A8C-4502-9503-91EB73541008}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
| {96805220-7A8C-4502-9503-91EB73541008}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
| {96805220-7A8C-4502-9503-91EB73541008}.Release|Any CPU.Build.0 = Release|Any CPU | ||
| EndGlobalSection | ||
| EndGlobal |
This file contains hidden or 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,13 @@ | ||
| namespace Lazyy | ||
| { | ||
| /// <summary> | ||
| /// интерфейс ленивого вычисления | ||
| /// </summary> | ||
| public interface ILazy<out T> | ||
| { | ||
| /// <summary> | ||
| /// вызывает вычисление один раз и возвращает один и тот же обьект, полученный при вычислении | ||
| /// </summary> | ||
| public T Get(); | ||
| } | ||
| } | ||
This file contains hidden or 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 @@ | ||
| using System; | ||
|
|
||
| namespace Lazyy | ||
| { | ||
| /// <summary> | ||
| /// создает обьекты для работы либо в однопоточном, либо в многопоточном режиме | ||
| /// </summary> | ||
| public static class LazyFactory | ||
| { | ||
| /// <summary> | ||
| /// создает обьект в однопоточном режиме | ||
| /// </summary> | ||
| public static ILazy<T> CreateSingleLazy<T>(Func<T> supplier) | ||
| => new LazySingle<T>(supplier); | ||
|
|
||
| /// <summary> | ||
| /// создает обьект в многопоточном режиме | ||
| /// </summary> | ||
| public static ILazy<T> CreateMultiLazy<T>(Func<T> supplier) | ||
| => new LazyMulti<T>(supplier); | ||
| } | ||
| } |
This file contains hidden or 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,46 @@ | ||
| using System; | ||
| using System.Threading; | ||
|
|
||
| namespace Lazyy | ||
| { | ||
| /// <summary> | ||
| /// реализация ILazy в многопоточном режиме | ||
| /// </summary> | ||
| public class LazyMulti<T> : ILazy<T> | ||
| { | ||
| private T _value; | ||
| private bool _isGenerated = false; | ||
| private Func<T> _supplier; | ||
| private readonly Object _lockObject = new(); | ||
|
|
||
| /// <summary> | ||
| /// создает обьект в многопоточном режиме | ||
| /// </summary> | ||
| public LazyMulti(Func<T> supplier) | ||
| => _supplier = supplier ?? throw new ArgumentNullException(); | ||
|
|
||
| /// <summary> | ||
| /// вызывает вычисление один раз и возвращает один и тот же обьект, полученный при вычислении | ||
| /// </summary> | ||
| public T Get() | ||
| { | ||
| if (_isGenerated) | ||
| { | ||
| return _value; | ||
| } | ||
|
|
||
| lock (_lockObject) | ||
| { | ||
| if (Volatile.Read(ref _isGenerated)) | ||
| { | ||
| return _value; | ||
| } | ||
|
|
||
| _value = _supplier(); | ||
This comment was marked as resolved.
Sorry, something went wrong.
This comment was marked as resolved.
Sorry, something went wrong. |
||
| Volatile.Write(ref _isGenerated, true); | ||
| _supplier = null; | ||
| return _value; | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or 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,36 @@ | ||
| using System; | ||
|
|
||
| namespace Lazyy | ||
| { | ||
| /// <summary> | ||
| /// реализация ILazy в однопоточном режиме | ||
| /// </summary> | ||
| public class LazySingle<T> : ILazy<T> | ||
| { | ||
| private T _value; | ||
| private Func<T> _supplier; | ||
| private bool _isGenerated = false; | ||
|
|
||
| /// <summary> | ||
| /// создает обьект в однопоточном режиме | ||
| /// </summary> | ||
| public LazySingle(Func<T> supplier) | ||
| => _supplier = supplier ?? throw new ArgumentNullException(); | ||
|
|
||
| /// <summary> | ||
| /// вызывает вычисление один раз и возвращает один и тот же обьект, полученный при вычислении | ||
| /// </summary> | ||
| public T Get() | ||
| { | ||
| if (_isGenerated) | ||
| { | ||
| return _value; | ||
| } | ||
|
|
||
| _isGenerated = true; | ||
| _value = _supplier(); | ||
| _supplier = null; | ||
| return _value; | ||
| } | ||
| } | ||
| } |
This file contains hidden or 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,9 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net5.0</TargetFramework> | ||
| <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS> | ||
| </PropertyGroup> | ||
|
|
||
| </Project> |
This file contains hidden or 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 @@ | ||
| using System; | ||
| using System.Threading; | ||
|
|
||
| namespace Lazyy | ||
| { | ||
| class Program | ||
| { | ||
| static void Main(string[] args) | ||
| { | ||
| var number1 = 2; | ||
| var number2 = 2; | ||
| var single = LazyFactory.CreateMultiLazy<int>(() => | ||
| { | ||
| number1 += number1; | ||
| return number1; | ||
| }); | ||
| var multi = LazyFactory.CreateMultiLazy<int>(() => | ||
| { | ||
| number2 *= number2; | ||
| return number2; | ||
| }); | ||
|
|
||
| var threads = new Thread[5]; | ||
| for (int i = 0; i < threads.Length; i++) | ||
| { | ||
| threads[i] = new Thread(() => multi.Get()); | ||
| } | ||
|
|
||
| foreach (var t in threads) | ||
| { | ||
| Console.WriteLine(multi.Get()); | ||
| Console.WriteLine("!!!"); | ||
| Console.WriteLine(single.Get()); | ||
| Console.WriteLine("!!!"); | ||
| } | ||
|
|
||
| foreach (var thread in threads) | ||
| { | ||
| thread.Start(); | ||
| } | ||
|
|
||
| foreach (var thread in threads) | ||
| { | ||
| thread.Join(); | ||
| } | ||
| } | ||
| } | ||
| } |
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.
This comment was marked as resolved.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.