Очередь без блокировки (или даже без ожидания) с несколькими потребителями - PullRequest
1 голос
/ 21 мая 2011

Я ищу документацию о том, как написать очередь MP / MC без блокировки или даже без ожидания.Я использую .Net 4.0.Нашел много кода на C ++, но я не очень знаком с моделями памяти, поэтому есть большая вероятность, что я буду вносить некоторые ошибки при портировании на C #.

Ответы [ 3 ]

2 голосов
/ 13 декабря 2016

Как вариант, есть алгоритм ограниченной очереди множественных производителей множественных потребителей Дмитрия Вьюкова . Я перенес алгоритм на .NET, вы можете найти исходники на github . Это очень быстро

Алгоритм постановки в очередь:

public bool TryEnqueue(object item)
{
    do
    {
        var buffer = _buffer; // prefetch the buffer pointer
        var pos = _enqueuePos; // fetch the current position where to enqueue the item
        var index = pos & _bufferMask; // precalculate the index in the buffer for that position
        var cell = buffer[index]; // fetch the cell by the index
        // If its sequence wasn't touched by other producers
        // and we can increment the enqueue position
        if (cell.Sequence == pos && Interlocked.CompareExchange(ref _enqueuePos, pos + 1, pos) == pos)
        {
            // write the item we want to enqueue
            Volatile.Write(ref buffer[index].Element, item);
            // bump the sequence
            buffer[index].Sequence = pos + 1;
            return true;
        }

        // If the queue is full we cannot enqueue and just return false
        if (cell.Sequence < pos)
        {
            return false;
        }

        // repeat the process if other producer managed to enqueue before us
    } while (true);
}

Алгоритм удаления:

public bool TryDequeue(out object result)
{
    do
    {
        var buffer = _buffer; // prefetch the buffer pointer
        var bufferMask = _bufferMask; // prefetch the buffer mask
        var pos = _dequeuePos; // fetch the current position from where we can dequeue an item
        var index = pos & bufferMask; // precalculate the index in the buffer for that position
        var cell = buffer[index]; // fetch the cell by the index
        // If its sequence was changed by a producer and wasn't changed by other consumers
        // and we can increment the dequeue position
        if (cell.Sequence == pos + 1 && Interlocked.CompareExchange(ref _dequeuePos, pos + 1, pos) == pos)
        {
            // read the item
            result = Volatile.Read(ref cell.Element);
            // update for the next round of the buffer
            buffer[index] = new Cell(pos + bufferMask + 1, null);
            return true;
        }

        // If the queue is empty return false
        if (cell.Sequence < pos + 1)
        {
            result = default(object);
            return false;
        }

        // repeat the process if other consumer managed to dequeue before us
    } while (true);
}
2 голосов
/ 21 мая 2011

Почему вы думаете, что вам нужна очередь без блокировки?Вы пытались использовать ConcurrentQueue<T>, возможно, заключенный в BlockingCollection<T>?

Трудно писать многопоточный код.Написание кода без блокировки еще сложнее, и вы не должны делать это самостоятельно, если вам действительно не нужно.

1 голос
/ 21 мая 2011

Мой первый шаг будет с ConcurrentQueue<T>, но вы можете абстрагировать свое хранилище данных за интерфейс, чтобы вы могли легко менять реализации.Затем сравните типичные сценарии и посмотрите, где возникают проблемы.Помните: преждевременная оптимизация - корень всего зла.Спроектируйте свою систему так, чтобы она была связана не с реализацией, а с контрактом, и тогда вы сможете оптимизировать свои реализации так, как вам захочется.

Я посмотрел на ConcurrentQueue<T> с помощью ILSpy и, похоже, это реализация без блокировки вна первый взгляд - так что велика вероятность, что это именно то, что вы ищете.

...