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

HW2 #4

Merged
merged 13 commits into from
Dec 4, 2023
16 changes: 15 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
name: Build
on: [push]
jobs:
build-Ubuntu:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-dotnet@v3
with:
dotnet-version: "7.x"
- name: Build
run: for f in $(find . -name "*.sln"); do dotnet build $f; done
- name: Run tests
run: for f in $(find . -name "*.sln"); do dotnet test $f; done
build-Windows:
runs-on: windows-latest
steps:
Expand All @@ -10,4 +21,7 @@ jobs:
dotnet-version: "7.x"
- name: Build
shell: bash
run: for f in $(find . -name "*.sln"); do dotnet build $f; done
run: for f in $(find . -name "*.sln"); do dotnet build $f; done
- name: Run tests
shell: bash
run: for f in $(find . -name "*.sln"); do dotnet test $f; done
Empty file removed .gitignore
Empty file.
14 changes: 14 additions & 0 deletions HW02LAZY/LAZY/LAZY.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
</ItemGroup>

</Project>
31 changes: 31 additions & 0 deletions HW02LAZY/LAZY/LAZY.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33213.308
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LAZY", "LAZY.csproj", "{276FC7DD-D798-45F9-8C47-316B22DFCC01}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LazyTests", "..\LazyTests\LazyTests.csproj", "{BDC0A084-C741-4787-87FD-DD66C13ABC5C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{276FC7DD-D798-45F9-8C47-316B22DFCC01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{276FC7DD-D798-45F9-8C47-316B22DFCC01}.Debug|Any CPU.Build.0 = Debug|Any CPU
{276FC7DD-D798-45F9-8C47-316B22DFCC01}.Release|Any CPU.ActiveCfg = Release|Any CPU
{276FC7DD-D798-45F9-8C47-316B22DFCC01}.Release|Any CPU.Build.0 = Release|Any CPU
{BDC0A084-C741-4787-87FD-DD66C13ABC5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BDC0A084-C741-4787-87FD-DD66C13ABC5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BDC0A084-C741-4787-87FD-DD66C13ABC5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BDC0A084-C741-4787-87FD-DD66C13ABC5C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6BC94BD4-BE73-414F-AC89-B2C3C2B80B0C}
EndGlobalSection
EndGlobal
116 changes: 116 additions & 0 deletions HW02LAZY/LAZY/Lazy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using System.Runtime.InteropServices;


namespace MyLazy;

public interface ILazy<T> {
T? Get();
}

/// <summary>
/// Thread non-safe realisation of built-in Lazy class
/// </summary>
/// <typeparam name="T">Type of supplier function returning value</typeparam>
public class LazySingleThread<T> : ILazy<T>
{
private bool _isCalculated = false;
private T? _result;
private Func<T> _supplier;

/// <summary>
/// Creates object of this class
/// </summary>
/// <param name="supplier">Function, providing calculation</param>
public LazySingleThread(Func<T> supplier)
{
_supplier = supplier;
}

/// <summary>
/// Calls for lazy initialised object. First time runs calculation
/// via supplier function. Following times returns precalculated value
/// </summary>
/// <returns>Result of running supplier function</returns>
public T? Get()
{
if (!_isCalculated) {
try
{
_result = _supplier();
}
catch
{
_result = default(T);
}
}
_isCalculated = true;
return _result;
}
}

/// <summary>
/// Thread safe realisation of built-in Lazy class
/// </summary>
/// <typeparam name="T">Type of supplier function returning value</typeparam>
public class LazyMultiThread<T> : ILazy<T>
{
private Object _lockObject = new();
private bool _isCalculated = false;
private T? _result;
private Func<T> _supplier;

/// <summary>
/// Creates object of this class
/// </summary>
/// <param name="supplier">Function, providing calculation</param>
public LazyMultiThread(Func<T> supplier)
{
_supplier = supplier;
}

/// <summary>
/// Calls for lazy initialised object. First time runs calculation
/// via supplier function. Following times returns precalculated value
/// </summary>
/// <returns>Result of running supplier function</returns>
public T? Get()
{
if (Volatile.Read(ref _isCalculated)) {
return _result;
}

lock (_lockObject)
{
if (Volatile.Read(ref _isCalculated))
return _result;

try
{
_result = _supplier();
Volatile.Write(ref _isCalculated, true);
}
catch
{
_result = default(T);
}

return _result;
}
}
}

public class Counter
{
private static int _counterValue = 0;
public static int CounterValue => _counterValue;
public static int Calculation()
{
return ++_counterValue;
}
}
internal class MyLazy
{
static void Main()
{
}
}
Comment on lines +111 to +116

Choose a reason for hiding this comment

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

вот это лучше удалить, зачем нам пустые классы?

122 changes: 122 additions & 0 deletions HW02LAZY/LazyTests/LazyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
using System.Diagnostics;
using System.Xml.Schema;
using MyLazy;

namespace LazyTests;

/// <summary>
/// Fraction calculation. Throws exception
/// if deviding zero
/// </summary>
public class Fraction
{
int _numerator;
int _denominator;

public Fraction(int numerator, int denominator)
{
_numerator = numerator;
_denominator = denominator;
}

public double Calculate()
{
if (_denominator != 0)
{
return (double)_numerator / _denominator;
}
else
{
throw new Exception("Zero division achtung");
}
}
}

/// <summary>
/// Counts calculation attempts from all working threads
/// </summary>
public class Counter
{
private int _counterValue = 0;
public int CounterValue => _counterValue;
public int Calculation()
{
return ++_counterValue;
}
}

[TestClass]
public class LazySingleThreadTests
{
[TestMethod]
public void ExceptionGetTest()
{
var successCalc = new Fraction(5, 2);
var exceptionCalc = new Fraction(5, 0);
var successLazy = new LazySingleThread<double>(successCalc.Calculate);
var exceptionLazy = new LazySingleThread<double>(exceptionCalc.Calculate);

Assert.IsTrue(successLazy.Get() == 2.5);
Assert.IsTrue(exceptionLazy.Get() == default(double));
}

[TestMethod]
public void GetTest()
{
var counter = new Counter();
var iterations = 20;
var lazyCalculator = new LazySingleThread<int>(counter.Calculation);

for (var i = 0; i < iterations; ++i)
lazyCalculator.Get();

Assert.IsTrue(lazyCalculator.Get() == 1);
Assert.IsTrue(counter.CounterValue == 1);
}
}

[TestClass]
public class LazyMultiThreadTests
{
[TestMethod]
public void ExceptionGetTest()
{
var successCalc = new Fraction(5, 2);
var exceptionCalc = new Fraction(5, 0);
var successLazy = new LazyMultiThread<double>(successCalc.Calculate);
var exceptionLazy = new LazyMultiThread<double>(exceptionCalc.Calculate);

Assert.IsTrue(successLazy.Get() == 2.5);
Assert.IsTrue(exceptionLazy.Get() == default(double));
}
[TestMethod]
public void GetTest()
{
var threadCount = 20;
var threadIterations = 20;
var threads = new Thread[threadCount];
var counter = new Counter();
var lazyCalculator = new LazyMultiThread<int>(counter.Calculation);

for (var i = 0; i < threadCount; ++i)
{
threads[i] = new Thread(() => {
for (var i = 0; i < threadIterations; ++i) {
lazyCalculator.Get();
}});
}

for (var i = 0; i < threadCount; ++i) {
threads[i].Start();
}

for (var i = 0; i < threadCount; ++i) {
threads[i].Join();
}

Assert.IsTrue(lazyCalculator.Get() == 1);
Assert.IsTrue(counter.CounterValue == 1);
}
}


22 changes: 22 additions & 0 deletions HW02LAZY/LazyTests/LazyTests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
<PackageReference Include="coverlet.collector" Version="3.1.2" />
</ItemGroup>

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

</Project>
1 change: 1 addition & 0 deletions HW02LAZY/LazyTests/Usings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using Microsoft.VisualStudio.TestTools.UnitTesting;