ConcurrentQueue.Net: Multithreaded Consumer

I had a very simple question that is more related to concepts ConcurrentQueue. The queue is FIFO. When multiple threads start accessing it, how do we guarantee FIFO? Suppose I said Apple, Oranges, Lemon, Peachand Apricot- in that order. The first TryTakeshould return Apple. But what happens when multiple threads start giving their own requests TryTake? Is it likely that when one thread can return Lemonbefore another thread can return Apple? I assume that other items will also be returned until the queue is empty. But will these returns be driven around the basic principles of FIFO?

+4
source share
1 answer

The behavior itself ConcurrentQueuewill always be FIFO.

When we say that threads "return" elements from ConcurrentQueue, we are talking about an operation that includes both deleting an object and performing some operation that allows you to observe what has been canceled. Whether it’s printing output or adding this item to another list, you don’t actually know which item was taken out of the queue until you check it.

FIFO, , , , . FIFO, , . , .

, FIFO, . ConcurrentQueue , , , .

( - ), , , , FIFO , .


.

  • 1 5000 ConcurrentQueue, .
  • ConcurrentQueue. " ".
  • (, ) , .

, . 50% . , , , . . , , .

- .

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;

namespace ConcurrentQueueExperiment
{
    class Program
    {
        static void Main(string[] args)
        {
            var inputQueue = new ConcurrentQueue<int>();
            var outputQueue = new ConcurrentQueue<int>();
            Enumerable.Range(1,5000).ToList().ForEach(inputQueue.Enqueue);
            while (inputQueue.Any())
            {
                Task.Factory.StartNew(() =>
                {
                    int dequeued;
                    if (inputQueue.TryDequeue(out dequeued))
                    {
                        outputQueue.Enqueue(dequeued);
                    }
                });
            }
            int output = 0;
            var previous = 0;
            while (outputQueue.TryDequeue(out output))
            {
                if(output!=previous+1)
                    Console.WriteLine("Out of sequence: {0}, {1}", previous, output);
                previous = output;
            }
            Console.WriteLine("Done!");
            Console.ReadLine();
        }
    }
}
+7

All Articles