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

Make realization if the thread-safe priority queue #10

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Conversation

kleo-53
Copy link
Owner

@kleo-53 kleo-53 commented Dec 21, 2022

No description provided.


public static class Program
{
public static void Main(string[] args)

Choose a reason for hiding this comment

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

Это не нужно. Как метод Main в современном .NET, так и точка входа в проекте, который по сути является библиотекой

public void EnqueueFromDifferentThreads()
{
var priorityQueue = new PriorityQueue<int>();
var threads = new Thread[3];

Choose a reason for hiding this comment

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

new Thread в современном .NET не нужен, есть пул потоков и Task.Run (или более высокоуровневые вещи, типа Parallel.ForEach)

correctValues[0] = "true";
correctValues[1] = "false";
correctValues[2] = "abobus";
Assert.AreEqual(correctValues, values);

Choose a reason for hiding this comment

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

Это не должно проходить :) Dequeue делается в разных потоках, и кто из них будет первым, тот и запишет в свою ячейку взятое из очереди значение. То есть даже если очередь возвращает всё как надо, values могут быть перемешанными

[Test]
public void EnqueueAndDequeueFromDifferentThreadsWithoutExceptions()
{
var priorityQueue = new PriorityQueue<string>();

Choose a reason for hiding this comment

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

Вынесли бы создание очереди в SetUp

thread.Join();
}
Assert.AreEqual(0, priorityQueue.Size);
}

Choose a reason for hiding this comment

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

Всего два потока, всего один раз...

/// Interface of thread-safe priority queue
/// </summary>
/// <typeparam name="TValue">Type of value</typeparam>
public interface IPriorityQueue<TValue>

Choose a reason for hiding this comment

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

Интерфейс не просили, хотя сделать его — вряд ли ошибка :)

{
lock (locker)
{
while (counter == 0)

Choose a reason for hiding this comment

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants