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

Priority Queue #7

Open
wants to merge 2 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
25 changes: 25 additions & 0 deletions PriorityQueue/PriorityQueue.Tests/PriorityQueue.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<IsPackable>false</IsPackable>

<RootNamespace>PiorityQueue.Tests</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.2.1" />
<PackageReference Include="NUnit.Analyzers" Version="3.3.0" />
<PackageReference Include="coverlet.collector" Version="3.1.2" />
</ItemGroup>

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

</Project>
90 changes: 90 additions & 0 deletions PriorityQueue/PriorityQueue.Tests/PriorityQueueTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
namespace PriorityQueue.Tests;

using PriorityQueue;

public class Tests
{
private PriorityQueue<int> _priorityQueue = new ();

[SetUp]
public void Setup()
{
_priorityQueue = new PriorityQueue<int>();
var tasks = new Task[10];

for (var i = 0; i < 10; i++)
{
var priority = i;
tasks[i] = Task.Run(() => EnqueueValues(priority));
}

Task.WaitAll(tasks);
Comment on lines +15 to +21

Choose a reason for hiding this comment

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

Это ведь SetUp, тут можно было просто последовательно значения в очередь сложить, и иметь отдельный тест на гонки при добавлении. Иначе независимость тестов нарушается

}

[Test]
public void DequeueShouldReturnFirstAddedValue()
{
var actualValue = _priorityQueue.Dequeue();
Assert.That(actualValue, Is.EqualTo(0));
}

[Test]
public void TestNumberOfElements()
{
Assert.That(_priorityQueue.Size, Is.EqualTo(100));
}

[Test]
public void DequeueShouldReturnAllElementsInCorrectOrder()
{
for (var i = 0; i < 10; i++)
{
for (var j = 0; j < 10; j++)
{
var actualValue = _priorityQueue.Dequeue();
Assert.That(actualValue, Is.EqualTo(j));
}
}
}

[Test]
public void ThreadsShouldWaitIfThereIsNoElementsInTheQueue()
{
for (var i = 0; i < 10; i++)
{
for (var j = 0; j < 10; j++)
{
var actualValue = _priorityQueue.Dequeue();
}
}

var tasks = new Task[5];
for (var taskNumber = 0; taskNumber < 5; taskNumber++)
{
tasks[taskNumber] = Task.Run(() => DequeueValueAndCompare(5));
}

for (var i = 0; i < 5; i++)
{
_priorityQueue.Enqueue(i, i);
}

Task.WaitAll(tasks);

Assert.That(_priorityQueue.Size, Is.EqualTo(0));
}

private void DequeueValueAndCompare(int expectedValue)
{
var actualValue = _priorityQueue.Dequeue();
Assert.That(actualValue, Is.LessThan(expectedValue));
}

private void EnqueueValues(int priority)
{
for (var value = 0; value < 10; value++)
{
_priorityQueue.Enqueue(value, priority);
}
}
}
1 change: 1 addition & 0 deletions PriorityQueue/PriorityQueue.Tests/Usings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using NUnit.Framework;
22 changes: 22 additions & 0 deletions PriorityQueue/PriorityQueue.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}") = "PriorityQueue", "PriorityQueue\PriorityQueue.csproj", "{A729599D-41D7-4A91-A884-3A50422DDC7E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PriorityQueue.Tests", "PriorityQueue.Tests\PriorityQueue.Tests.csproj", "{EEB7DAD5-E485-455F-A363-5DD9765E2AE4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A729599D-41D7-4A91-A884-3A50422DDC7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A729599D-41D7-4A91-A884-3A50422DDC7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A729599D-41D7-4A91-A884-3A50422DDC7E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A729599D-41D7-4A91-A884-3A50422DDC7E}.Release|Any CPU.Build.0 = Release|Any CPU
{EEB7DAD5-E485-455F-A363-5DD9765E2AE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EEB7DAD5-E485-455F-A363-5DD9765E2AE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EEB7DAD5-E485-455F-A363-5DD9765E2AE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EEB7DAD5-E485-455F-A363-5DD9765E2AE4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
90 changes: 90 additions & 0 deletions PriorityQueue/PriorityQueue/PriorityQueue.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
namespace PriorityQueue;

using System.Linq;

/// <summary>
/// Thread safe priority queue.
/// </summary>
/// <typeparam name="TValue">Type of queue elements.</typeparam>
public class PriorityQueue<TValue>
{
private List<QueueElement<TValue>> _queueElementList = new ();

/// <summary>
/// Gets count of elements in the queue.
/// </summary>
public int Size => _queueElementList.Count;

/// <summary>
/// Enqueues value with given priority.
/// </summary>
/// <param name="value">Element value.</param>
/// <param name="priority">Priority of the element.</param>
public void Enqueue(TValue value, int priority)
{
lock (_queueElementList)
{
var newElement = new QueueElement<TValue>(value, priority);
_queueElementList.Add(newElement);

Monitor.PulseAll(_queueElementList);
}
}

/// <summary>
/// Gets element with the highest priority and removes it from the queue.
/// </summary>
/// <returns></returns>
public TValue Dequeue()
{
lock (_queueElementList)
{
while (Size == 0)

Choose a reason for hiding this comment

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

Кажется, Size лучше быть volatile-полем, потому что этот поток может ещё не увидеть изменений из 28-й строки и снова встанет на Wait — дедлок. В .NET memory model вроде есть что-то про то, что взятие/освобождение замка влечёт синхронизацию памяти, так что на практике, скорее всего, всё будет хорошо, но мне кажется, лучше избегать таких проблем явно.

{
Monitor.Wait(_queueElementList);
}

return GetAndRemove().Value;
}
}

private QueueElement<TValue> GetAndRemove()
{
var maxElement = _queueElementList.Max() ?? throw new ArgumentNullException();
_queueElementList.Remove(maxElement);
return maxElement;
}

/// <summary>
/// Class for elements of the queue.
/// </summary>
/// <typeparam name="TValue">Elements value type.</typeparam>
private class QueueElement<TValue> : IComparable<QueueElement<TValue>>

Choose a reason for hiding this comment

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

Линтер по делу ругается, тут лишний параметр-тип

{
/// <summary>
/// Element priority.
/// </summary>
public int Priority { get; }

/// <summary>
/// Element value.
/// </summary>
public TValue Value { get; }

/// <summary>
/// Initializes a new instance of the <see cref="QueueElement"/> class.
/// </summary>
/// <param name="value"></param>
/// <param name="priority"></param>
public QueueElement(TValue value, int priority)
{
Priority = priority;
Value = value;
}

public int CompareTo(QueueElement<TValue>? other)
{
return this.Priority.CompareTo((other ?? throw new ArgumentNullException()).Priority);
}
}
}
10 changes: 10 additions & 0 deletions PriorityQueue/PriorityQueue/PriorityQueue.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

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

</Project>