public JobEngine(int maxConcurrentJobs, bool testMode = false)
 {
     Testmode = testMode;
     MaxConcurrentJobs = maxConcurrentJobs;
     JobQueue= new ConcurrentPriorityQueue<int, IJob>();
     CurrentJobs = new LinkedList<IJob>();
 }
Example #2
0
        public SmcTicketThread(SmcDto smcDto, ClientSettings clientSettings,
                               BrokerSettings brokerSettings, IMqttClientConfiguration mqttClientConfiguration,
                               IMqttClientMethods mqttClientMethods, Topic topic,
                               CommandRules commandRules, IEventService eventService, IForwarderSenderService forwarderSenderService)
        {
            Smc                             = smcDto;
            _eventService                   = eventService;
            _forwarderSenderService         = forwarderSenderService;
            Tickets                         = new ConcurrentPriorityQueue <TicketThreadObject>();
            _executingCommandSemaphore      = new SemaphoreSlim(1, 1);
            _waitingCommandMessageSemaphore = new SemaphoreSlim(1, 1);
            _answerSemaphore                = new SemaphoreSlim(1, 1);

            var localClientSettings = new ClientSettings
            {
                ClientId = clientSettings.ClientId, ClientName = clientSettings.ClientName
            };

            localClientSettings.ClientId   = localClientSettings.ClientId.Replace("serial", smcDto.Serial);
            localClientSettings.ClientName = localClientSettings.ClientName.Replace("serial", smcDto.Serial);
            localClientSettings.DebugMode  = clientSettings.DebugMode;
            localClientSettings.AutoReconnectDelayInSeconds = clientSettings.AutoReconnectDelayInSeconds;
            var localTopic = new Topic {
                Address = topic.Address, QoS = topic.QoS
            };

            localTopic.Address = localTopic.Address
                                 .Replace("{smc-or-meter}", CommandDeviceType.Smc.ToString().ToLower())
                                 .Replace("{serial}", smcDto.Serial);
            _mqttClient = new IoGMqttClient(localClientSettings, brokerSettings, mqttClientConfiguration,
                                            mqttClientMethods);
            _mqttClient.Subscribe(localTopic);
            _mqttClient.MessageReceivedHandler += ReceivedUpdate;
            _commandRules = commandRules;
        }
Example #3
0
        public void GetEnumerator()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Enqueue a few elements into the queue.
            queue.Enqueue(1.0, 2);
            queue.Enqueue(3.0, 6);
            queue.Enqueue(2.0, 4);

            // Use the enumerator of queue (using disposes it when we're finished).
            using (IEnumerator <PriorityValuePair <int> > enumerator = queue.GetEnumerator())
            {
                // Expect the first element to have the highest priority, and expect MoveNext() to
                // return true until the last element. After the end of the heap is reached, it
                // then returns false.
                // Note: Since the heap implementing the queue internally doesn't guarantee the
                // order of elements after the first, we can only be certain of the root element
                // and after that we really can't be sure of the order -- just the length.
                Assert.That(enumerator.MoveNext(), Is.True);
                Assert.That(enumerator.Current.Value, Is.EqualTo(6));
                Assert.That(enumerator.MoveNext(), Is.True);
                Assert.That(enumerator.MoveNext(), Is.True);
                Assert.That(enumerator.MoveNext(), Is.False);
            }
        }
Example #4
0
        public void PropertyPriorityAdjustment()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that PriorityAdjustment reports 0.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(0.0));

            // Enqueue an element in the queue.
            queue.Enqueue(1.0, 1);

            // Ensure that PriorityAdjustment reports 1.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(1L * ConcurrentPriorityQueue <int> .EPSILON));

            // Enqueue an element in the queue.
            queue.Enqueue(1.0, 1);

            // Ensure that PriorityAdjustment reports 2.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(2L * ConcurrentPriorityQueue <int> .EPSILON));

            // Clear the queue.
            queue.Clear();

            // Ensure that PriorityAdjustment reports 0.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(0.0));
        }
Example #5
0
        public void PropertyNumQueuedItems()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that NumQueuedItems reports 0.
            Assert.That(queue.NumQueuedItems, Is.EqualTo(0L));

            // Enqueue an element in the queue.
            queue.Enqueue(1.0, 1);

            // Ensure that NumQueuedItems reports 1.
            Assert.That(queue.NumQueuedItems, Is.EqualTo(1L));

            // Enqueue an element in the queue.
            queue.Enqueue(1.0, 1);

            // Ensure that NumQueuedItems reports 2.
            Assert.That(queue.NumQueuedItems, Is.EqualTo(2L));

            // Clear the queue.
            queue.Clear();

            // Ensure that NumQueuedItems reports 0.
            Assert.That(queue.NumQueuedItems, Is.EqualTo(0L));
        }
Example #6
0
        private void checkForSales()
        {
            var tempBuyQueue = new ConcurrentPriorityQueue <int, int>();

            while (ss.BuyQueue.Count > 0)
            {
                var  buyer         = ss.BuyQueue.Dequeue();
                var  tempSellQueue = new ConcurrentPriorityQueue <int, int>();
                bool buyerFound    = false;
                while (ss.SellQueue.Count > 0 && buyerFound == false)
                {
                    var seller = ss.SellQueue.Dequeue();
                    if (seller <= buyer)
                    {
                        // Sold
                        buyerFound = true;
                        break;
                    }
                    else
                    {
                        tempSellQueue.Enqueue(seller, seller);
                    }
                }
                if (!buyerFound)
                {
                    tempBuyQueue.Enqueue(buyer, buyer);
                }

                ss.SellQueue = tempSellQueue;
            }
            ss.BuyQueue = tempBuyQueue;
        }
        public static ListNode Merge(ListNode[] lists)
        {
            ListNode mergedList     = null;
            ListNode mergedListTail = null;

            ConcurrentPriorityQueue <ListNode, int> queue = new ConcurrentPriorityQueue <ListNode, int>();

            for (int i = 0; i < lists.Length; i++)
            {
                queue.Enqueue(lists[i], -lists[i].Value);
            }

            mergedListTail = GetMinValue(queue);
            mergedList     = mergedListTail;

            while (mergedListTail != null)
            {
                ListNode nodeWithMinValue = GetMinValue(queue);

                mergedListTail.Next = nodeWithMinValue;
                mergedListTail      = nodeWithMinValue;
            }

            return(mergedList);
        }
Example #8
0
        private void checkForSales()
        {
            var tempBuyQueue = new ConcurrentPriorityQueue<int, int>();

            while (ss.BuyQueue.Count > 0)
            {
                var buyer = ss.BuyQueue.Dequeue();
                var tempSellQueue = new ConcurrentPriorityQueue<int, int>();
                bool buyerFound = false;
                while (ss.SellQueue.Count > 0 && buyerFound == false)
                {
                    var seller = ss.SellQueue.Dequeue();
                    if (seller <= buyer)
                    {
                        // Sold
                        buyerFound = true;
                        break;
                    }
                    else
                    {
                        tempSellQueue.Enqueue(seller, seller);
                    }

                }
                if (!buyerFound)
                {
                    tempBuyQueue.Enqueue(buyer, buyer);
                }

                ss.SellQueue = tempSellQueue;
            }
            ss.BuyQueue = tempBuyQueue;
        }
 public ChunkTaskManager()
 {
     requestPool        = new ConcurrentPool <ChunkTaskRequest>(() => { return(new ChunkTaskRequest()); });
     requests           = new ConcurrentPriorityQueue <ChunkTaskRequest>(new ChunkTaskRequestComparer());
     taskCallbackMethod = new ChunkTask.Callback(TaskCallback);
     activeRequests     = new Dictionary <ChunkTaskRequest, ChunkTaskRequest>(concurrencyLevel);
 }
        public async Task ConcurrentEnqueueSequentialDequeue()
        {
            var q      = new ConcurrentPriorityQueue <int>();
            var values = new int[10000];
            var r      = new Random(0);

            for (int i = 0; i < values.Length; i++)
            {
                values[i] = 0x7FFFFFFF & r.Next();
            }

            await Task.WhenAll(values.Select(value => Task.Run(() => q.Enqueue(value, value))));

            int dequeuedPriority, dequeuedValue;
            var dequeuedValues = new List <int>();

            while (q.TryDequeue(out dequeuedPriority, out dequeuedValue))
            {
                dequeuedValues.Add(dequeuedValue);
            }

            Array.Sort(values);
            dequeuedValues.Sort();
            XAssert.IsTrue(values.SequenceEqual(dequeuedValues));
        }
Example #11
0
        public void Remove()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Create and store a few elements.
            PriorityValuePair <int> elem1 = new PriorityValuePair <int>(1.0, 2);
            PriorityValuePair <int> elem2 = new PriorityValuePair <int>(2.0, 4);
            PriorityValuePair <int> elem3 = new PriorityValuePair <int>(3.0, 6);

            // Expect Remove() to return false for an empty queue.
            Assert.That(queue.Remove(elem1), Is.False);

            // Enqueue 2 of the elements into the heap.
            queue.Enqueue(elem2);
            queue.Enqueue(elem3);

            // Expect Remove() to return false for elem1, indicating the element was removed
            // (since it doesn't belong to the heap and can't be found). This tests the if-else
            // case for when the provided element isn't found in the heap.
            Assert.That(queue.Remove(elem1), Is.False);

            // Expect Remove() to return true for elem2, indicating the element was removed
            // (since it belongs to the heap and can be found). This tests the if-else case for
            // when Count is 2 or greater.
            Assert.That(queue.Remove(elem2), Is.True);

            // Expect Remove() to return true for elem3, indicating the element was removed
            // (since it belongs to the heap and can be found). This tests the if-else case for
            // when Count equals 1.
            Assert.That(queue.Remove(elem3), Is.True);
        }
Example #12
0
        public void CopyTo()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Create a new array of size 5.
            PriorityValuePair <int>[] arrayCopy = new PriorityValuePair <int> [5];

            // Enqueue 3 elements into the queue.
            PriorityValuePair <int> elem = new PriorityValuePair <int>(3.0, 6);

            queue.Enqueue(1.0, 2);
            queue.Enqueue(elem);
            queue.Enqueue(2.0, 4);

            // Copy the queue data to the array, starting from index 1 (not 0).
            queue.CopyTo(arrayCopy, 1);

            // Expect the first array index to be unset, but all the rest to be set.
            // Note: The order of elements after the first can't be guaranteed, because the heap
            // implementing the queue internally doesn't store things in an exact linear order,
            // but we can be sure that the elements aren't going to be equal to null because we
            // set them.
            Assert.That(arrayCopy[0], Is.EqualTo(null));
            Assert.That(arrayCopy[1], Is.EqualTo(elem));
            Assert.That(arrayCopy[2], Is.Not.EqualTo(null));
            Assert.That(arrayCopy[3], Is.Not.EqualTo(null));
            Assert.That(arrayCopy[4], Is.EqualTo(null));
        }
Example #13
0
 public Loader(int threadsN)
 {
     MAX_THREAD_COUNT = threadsN;
     _threadCount = 0;
     _dic = new ShortDictionary<string, byte[]>(10);
     _queue = new ConcurrentPriorityQueue<string>();
 }
Example #14
0
        public void PropertyIsReadOnly()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that IsReadOnly always reports FALSE.
            Assert.That(queue.IsReadOnly, Is.False);
        }
        public void EqualsForValueTypes()
        {
            var target = new ConcurrentPriorityQueue <int, int>(4);

            Assert.IsTrue(target.Equals(1, 1));
            Assert.IsFalse(target.Equals(1, 2));
            Assert.IsFalse(target.Equals(2, 1));
        }
Example #16
0
        public void ConstructorParameterless()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Nothing to test about the queue, but check that NumQueuedItems inits to 0.
            Assert.That(queue.NumQueuedItems, Is.EqualTo(0L));
        }
Example #17
0
        public RconClient()
        {
            queue      = new ConcurrentPriorityQueue <KeyValuePair <Command, EventHandler <CommandExecutedEventArgs> >, int>();
            resetEvent = new ManualResetEvent(false);
            Thread workerThread = new Thread(ExecuteCommandWorker);

            workerThread.IsBackground = true;
            workerThread.Start();
            rcon = new RconBase();
        }
        public void EqualsForObjects()
        {
            var target = new ConcurrentPriorityQueue <string, int>(4);

            Assert.IsTrue(target.Equals("a", "a"));
            Assert.IsFalse(target.Equals("a", "b"));
            Assert.IsFalse(target.Equals("a", null));
            Assert.IsFalse(target.Equals(null, "a"));
            Assert.IsTrue(target.Equals(null, null));
        }
Example #19
0
        public void Dequeue()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that the heap is empty.
            Assert.That(queue.Count, Is.EqualTo(0));

            // Expect Dequeue() to return null for an empty heap.
            Assert.That(queue.Dequeue(), Is.EqualTo(null));

            // Ensure that the heap is empty.
            Assert.That(queue.Count, Is.EqualTo(0));

            // Store an element and insert it into the heap.
            PriorityValuePair <int> elem = new PriorityValuePair <int>(1.0, 2);

            queue.Enqueue(elem);

            // Ensure that the element was inserted into the heap.
            Assert.That(queue.Count, Is.EqualTo(1));
            Assert.That(queue.Peek(), Is.EqualTo(elem));

            // Ensure that the PriorityAdjustment was incremented.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(ConcurrentPriorityQueue <int> .EPSILON));

            // Ensure that the returned element points to the same object we stored earlier.
            Assert.That(queue.Dequeue(), Is.EqualTo(elem));

            // Ensure that the element was removed from the heap.
            Assert.That(queue.Count, Is.EqualTo(0));

            // Ensure that the PriorityAdjustment was reset once the queue became empty.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(0.0));

            // Enqueue 5 items with the same priority.
            PriorityValuePair <int> elem2 = new PriorityValuePair <int>(2.0, 0);
            PriorityValuePair <int> elem3 = new PriorityValuePair <int>(2.0, 2);
            PriorityValuePair <int> elem4 = new PriorityValuePair <int>(2.0, 4);
            PriorityValuePair <int> elem5 = new PriorityValuePair <int>(2.0, 6);
            PriorityValuePair <int> elem6 = new PriorityValuePair <int>(2.0, 8);

            queue.Enqueue(elem2);
            queue.Enqueue(elem3);
            queue.Enqueue(elem4);
            queue.Enqueue(elem5);
            queue.Enqueue(elem6);

            //// Ensure that Dequeue() returns the items in the order they were enqueued.
            Assert.That(queue.Dequeue(), Is.EqualTo(elem2));
            Assert.That(queue.Dequeue(), Is.EqualTo(elem3));
            Assert.That(queue.Dequeue(), Is.EqualTo(elem4));
            Assert.That(queue.Dequeue(), Is.EqualTo(elem5));
            Assert.That(queue.Dequeue(), Is.EqualTo(elem6));
        }
Example #20
0
        public AStar(PuzzleNode goalNode)
        {
            code = "AS";
            longName = "A* Search";
            longName = "Greedy Best-First Search";
            Frontier = new ConcurrentPriorityQueue<node, int>();
            ClosedList = new HashSet<node>();
            GoalNode = goalNode;
            v = new TreeVisitor();

        }
        public string Solve()
        {
            var graphLines  = _input.Split("\n").Select(line => GraphCoordinatesFromLine(line)).ToArray();
            var graph       = new Dictionary <char, ISet <char> >();
            var keys        = new HashSet <char>();
            var entryDegree = new Dictionary <char, int>();

            foreach (var(x, y) in graphLines)
            {
                if (!graph.ContainsKey(x))
                {
                    graph.Add(x, new HashSet <char>());
                }
                graph[x].Add(y);

                if (!entryDegree.ContainsKey(y))
                {
                    entryDegree.Add(y, 0);
                }
                ++entryDegree[y];
                keys.Add(x);
                keys.Add(y);
            }

            var priorityQueue = new ConcurrentPriorityQueue <char, int>();

            foreach (char v in keys)
            {
                if (!entryDegree.ContainsKey(v))
                {
                    priorityQueue.Enqueue(v, -(v - 'A'));
                }
            }

            StringBuilder answer = new StringBuilder();

            while (priorityQueue.Count != 0)
            {
                char u = priorityQueue.Dequeue();
                answer.Append(u);
                if (graph.ContainsKey(u))
                {
                    foreach (char v in graph[u])
                    {
                        --entryDegree[v];
                        if (entryDegree[v] == 0)
                        {
                            priorityQueue.Enqueue(v, -(v - 'A'));
                        }
                    }
                }
            }
            return(answer.ToString());
        }
Example #22
0
        /// <summary>
        /// implmentation of the Search method.
        /// </summary>
        /// <param name="searchable"> the searching problem to search in. </param>
        /// <returns> Solution object that includes the nodes of the route from the initial node to the goal.</returns>
        public override Solution <T> Search(ISearchable <T> searchable)
        {
            ConcurrentPriorityQueue <State <T>, double> open = new ConcurrentPriorityQueue <State <T>, double>();

            closed = new HashSet <State <T> >();

            State <T> initialState = searchable.GetInitialState();

            open.Enqueue(initialState, 0);
            while (open.Count != 0)
            {
                State <T> node = open.Dequeue();
                evaluatedNodes++;
                if (node.Equals(searchable.GetGoalState()))
                {
                    return(new Solution <T>(BackTrace(searchable), GetNumberOfNodesEvaluated()));
                }

                closed.Add(node);
                foreach (State <T> adjacent in searchable.GetAllPossibleStates(node))
                {
                    if (!closed.Contains(adjacent) && !open.Contains(adjacent))
                    {
                        adjacent.CameFrom  = node;
                        adjacent.TotalCost = node.TotalCost + adjacent.Cost;
                        open.Enqueue(adjacent, adjacent.TotalCost);
                    }
                    else
                    {
                        if ((node.TotalCost + adjacent.Cost) < adjacent.TotalCost)
                        {
                            adjacent.CameFrom  = node;
                            adjacent.TotalCost = node.TotalCost + adjacent.Cost;

                            if (open.Contains(adjacent))
                            {
                                open.UpdatePriority(adjacent, adjacent.TotalCost);
                            }
                            else
                            {
                                closed.Remove(adjacent);
                                open.Enqueue(adjacent, adjacent.TotalCost);
                            }
                        }
                    }
                }
            }

            return(null);
        }
    public delegate void Write(T block);                      // Called by only one thread.

    public ParallelWorkProcessor(Read read, Process process, Write write, int numWorkers = 0)
    {
        _read        = read;
        _process     = process;
        _write       = write;
        numWorkers   = (numWorkers > 0) ? numWorkers : Environment.ProcessorCount;
        _workPool    = new SemaphoreSlim(numWorkers * 2);
        _inputQueue  = new BlockingCollection <WorkItem>(numWorkers);
        _outputQueue = new ConcurrentPriorityQueue <int, T>();
        _workers     = new Task[numWorkers];
        startWorkers();
        Task.Factory.StartNew(enqueueWorkItems);
        _multiplexor = Task.Factory.StartNew(multiplex);
    }
Example #24
0
        public void Add()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that the queue is empty.
            Assert.That(queue.Count, Is.EqualTo(0));

            // Call Add() to insert a new element to the queue as a KeyValuePair.
            queue.Add(new PriorityValuePair <int>(1.0, 2));

            // Expect a value of 2 on the first item to be removed after adding it.
            Assert.That(queue.Dequeue().Value, Is.EqualTo(2));
        }
Example #25
0
 ConcurrentPriorityTaskRunner()
 {
     __queue  = new ConcurrentPriorityQueue <Task>();
     __state  = TaskRunnerState.Stopped;
     __thread = null;
     __runningCriticalTasks        = 0;
     __runningNoncriticalTasks     = 0;
     __waitingCriticalTasks        = 0;
     __waitingNoncriticalTasks     = 0;
     __runningCriticalTasksLock    = new object();
     __runningNoncriticalTasksLock = new object();
     __waitingCriticalTasksLock    = new object();
     __waitingNoncriticalTasksLock = new object();
 }
Example #26
0
        public void PropertyIsEmpty()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that IsEmpty reports TRUE.
            Assert.That(queue.IsEmpty, Is.True);

            // Enqueue an element in the queue.
            queue.Enqueue(1.0, 1);

            // Ensure that IsEmpty now reports FALSE.
            Assert.That(queue.IsEmpty, Is.False);
        }
        public void ConcurrentReadWritePerformance()
        {
            const int count = 10;
            var times = new int[count];
            var c = new ConcurrentPriorityQueue<int>();
            for (var i = 0; i < count; i++)
            {
                var t = new CollectionReadWritePerformance(c, 10, 5, 10000);
                times[i] = t.Run().Milliseconds;
                c.Clear();
            }

            Console.WriteLine("Avg: {0}, Min: {1}, Max: {2}", times.Average(), times.Min(), times.Max());
            Console.WriteLine(string.Join(" ", times));
        }
        public void RaceWithStats()
        {
            const int capacity = 1000000;
            const int threadsCount = 100;
            const int count = capacity / threadsCount;
            var target = new ConcurrentPriorityQueue<DateTime>();
            var execStats = new List<ExecWithStats>();
            var threadWait = new CountdownEvent(threadsCount);

            // odd threads will enqueue elements, while even threads will dequeue
            // obviously there will be a race condition and especially in the beginning dequeue will throw, because queue will often be empty
            // the total number of exceptions on dequeue threads will correspond the the number of items left in the queue

            for (var i = 0; i < threadsCount; i++)
            {
                ExecWithStats exec;
                if (i % 2 != 0)
                {
                    exec = new ExecWithStats(string.Format("Add {0} elements", count), count, () => target.Add( new DateTime()), threadWait);
                }
                else
                {
                    exec = new ExecWithStats(string.Format("Take {0} elements", count), count, () => target.Take(), threadWait);
                }

                execStats.Add(exec);

                var thread = new Thread(() => exec.Exec());
                thread.Start();
            }

            // Wait for all threads in pool to calculate.
            threadWait.Wait();

            // Output stats summary
            ExecWithStats.OutputStatsSummary(execStats);

            // Output queue state
            Console.WriteLine("Queue count:{0}, capacity:{1}", target.Count, target.Capacity);

            // Un-comment for a detailed list of stats
            //Console.WriteLine("---------------------");
            //foreach (var execStat in execStats)
            //{
            //    var stats = execStat.GetStats();
            //    Console.WriteLine("Name:{0}, Min: {1}, Median: {2}, Max {3}, Exceptions: {4}", stats.Name, stats.Min, stats.Med, stats.Max, stats.ExceptionsCount);
            //}
        }
        public void RaceWithStats()
        {
            const int capacity     = 1000000;
            const int threadsCount = 100;
            const int count        = capacity / threadsCount;
            var       target       = new ConcurrentPriorityQueue <string, DateTime>();
            var       execStats    = new List <ExecWithStats>();
            var       threadWait   = new CountdownEvent(threadsCount);

            // odd threads will enqueue elements, while even threads will dequeue
            // obviously there will be a race condition and especially in the beginning dequeue will throw, because queue will often be empty
            // the total number of exceptions on dequeue threads will correspond the the number of items left in the queue

            for (var i = 0; i < threadsCount; i++)
            {
                ExecWithStats exec;
                if (i % 2 != 0)
                {
                    exec = new ExecWithStats(string.Format("Enqueue {0} elements", count), count, () => target.Enqueue("a", new DateTime()), threadWait);
                }
                else
                {
                    exec = new ExecWithStats(string.Format("Dequeue {0} elements", count), count, () => target.Dequeue(), threadWait);
                }

                execStats.Add(exec);

                var thread = new Thread(() => exec.Exec());
                thread.Start();
            }

            // Wait for all threads in pool to calculate.
            threadWait.Wait();

            // Output stats summary
            ExecWithStats.OutputStatsSummary(execStats);

            // Output queue state
            Console.WriteLine("Queue count:{0}, capacity:{1}", target.Count, target.Capacity);

            // Un-comment for a detailed list of stats
            //Console.WriteLine("---------------------");
            //foreach (var execStat in execStats)
            //{
            //    var stats = execStat.GetStats();
            //    Console.WriteLine("Name:{0}, Min: {1}, Median: {2}, Max {3}, Exceptions: {4}", stats.Name, stats.Min, stats.Med, stats.Max, stats.ExceptionsCount);
            //}
        }
Example #30
0
        public void Peek()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that the heap is empty.
            Assert.That(queue.Count, Is.EqualTo(0));

            // Expect Peek() to return null for an empty heap.
            Assert.That(queue.Peek(), Is.EqualTo(null));

            // Ensure that the queue is empty.
            Assert.That(queue.Count, Is.EqualTo(0));

            // Store an element and insert it into the queue.
            PriorityValuePair <int> elem1 = new PriorityValuePair <int>(1.0, 2);

            queue.Enqueue(elem1);

            // Ensure that the element was inserted into the queue at the front.
            Assert.That(queue.Count, Is.EqualTo(1));
            Assert.That(queue.Peek(), Is.EqualTo(elem1));

            // Ensure that the element was not removed from the heap.
            Assert.That(queue.Count, Is.EqualTo(1));

            // Insert another element with higher priority than the last.
            PriorityValuePair <int> elem2 = new PriorityValuePair <int>(2.0, 4);

            queue.Enqueue(elem2);

            // Ensure that Peek() returns the new front element.
            Assert.That(queue.Peek(), Is.EqualTo(elem2));

            // Insert another element with the same priority as the last.
            PriorityValuePair <int> elem3 = new PriorityValuePair <int>(2.0, 6);

            queue.Enqueue(elem3);

            // Ensure that Peek() returns still returns the first value with that priority.
            Assert.That(queue.Peek(), Is.EqualTo(elem2));

            // Remove the element from the queue.
            queue.Dequeue();

            // Ensure that Peek() returns now returns the other value with the same priorty.
            Assert.That(queue.Peek(), Is.EqualTo(elem3));
        }
        private static ListNode GetMinValue(ConcurrentPriorityQueue <ListNode, int> queue)
        {
            if (queue.Count == 0)
            {
                return(null);
            }

            ListNode minNode = queue.Dequeue();

            if (minNode.Next != null)
            {
                queue.Enqueue(minNode.Next, -minNode.Next.Value);
            }

            return(minNode);
        }
        public void EnqueueDequeue()
        {
            var target = new ConcurrentPriorityQueue <string, int>(7);

            target.Enqueue("a", 7);
            target.Enqueue("b", 6);
            target.Enqueue("c", 5);
            Assert.AreEqual("a", target.Dequeue());
            target.Enqueue("d", 4);
            Assert.AreEqual("b", target.Dequeue());
            target.Enqueue("a", 7);
            Assert.AreEqual("a", target.Dequeue());
            Assert.AreEqual("c", target.Dequeue());
            Assert.AreEqual("d", target.Dequeue());
            Assert.AreEqual(0, target.Count);
        }
Example #33
0
        public void ConcurrentReadWritePerformance()
        {
            const int count = 10;
            var       times = new int[count];
            var       c     = new ConcurrentPriorityQueue <int>();

            for (var i = 0; i < count; i++)
            {
                var t = new CollectionReadWritePerformance(c, 10, 5, 10000);
                times[i] = t.Run().Milliseconds;
                c.Clear();
            }

            Console.WriteLine("Avg: {0}, Min: {1}, Max: {2}", times.Average(), times.Min(), times.Max());
            Console.WriteLine(string.Join(" ", times));
        }
Example #34
0
        public void PropertyCount()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that Count reports 0.
            Assert.That(queue.Count, Is.EqualTo(0));

            // Enqueue 3 elements in the queue.
            queue.Enqueue(1.0, 1);
            queue.Enqueue(3.0, 3);
            queue.Enqueue(2.0, 2);

            // Ensure that Count now reports 3.
            Assert.That(queue.Count, Is.EqualTo(3));
        }
Example #35
0
        public override List <Node> Search(Node start, Node end)
        {
            var parentMap     = new Dictionary <Node, Node>();
            var priorityQueue = new ConcurrentPriorityQueue <Node, double>();

            priorityQueue.Enqueue(start, start.Cost);

            while (priorityQueue.Count > 0)
            {
                var current = priorityQueue.Dequeue();

                if (current.IsVisited)
                {
                    continue;
                }

                current.IsVisited = true;

                //if (current.Equals(end)) break;

                foreach (var edge in current.Edges)
                {
                    var neighbor     = edge.End;
                    var newCost      = current.Cost + edge.Weight;
                    var neighborCost = neighbor.Cost;

                    if (newCost > neighborCost)
                    {
                        continue;
                    }

                    neighbor.Cost = newCost;
                    try
                    {
                        parentMap.Add(neighbor, current);
                        var priority = newCost;
                        priorityQueue.Enqueue(neighbor, priority);
                    }
                    catch (Exception)
                    {
                        //Console.WriteLine("Tried adding node that already exists. Look into this");
                    }
                }
            }

            return(ReconstructPath(parentMap, start, end));
        }
Example #36
0
        public void Contains()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Create and store a new element.
            PriorityValuePair <int> elem = new PriorityValuePair <int>(1.0, 2);

            // Ensure the queue contains the element.
            Assert.That(queue.Contains(elem), Is.False);

            // Enqueue it in the queue.
            queue.Enqueue(elem);

            // Ensure the queue now contains the element.
            Assert.That(queue.Contains(elem), Is.True);
        }
        public void MultiThreadEnqueue()
        {
            const int capacity = 1000000;
            const int threadsCount = 100;
            const int count = capacity / threadsCount;
            var target = new ConcurrentPriorityQueue<DateTime>();

            var execStats = new ExecWithStats[threadsCount];

            var watcher = new Stopwatch();

            // several threads enqueue elements
            watcher.Start();
            Parallel.For(0, threadsCount, index =>
            {
                execStats[index] = new ExecWithStats(string.Format("Add {0}", count), count, () => target.Add(new DateTime()));
                execStats[index].Exec();
            });

            watcher.Stop();
            Assert.AreEqual(capacity, target.Count);
            Console.WriteLine("{0} threads each enqueue {1} elements. total time: {2}\n", threadsCount, count, watcher.Elapsed);
            ExecWithStats.OutputStatsSummary(execStats);

            // several threads dequeue elements
            watcher.Start();
            Parallel.For(0, threadsCount, index =>
            {
                execStats[index] = new ExecWithStats(string.Format("Take {0}", count), count, () => target.Take());
                execStats[index].Exec();
            });
            watcher.Stop();
            Assert.AreEqual(0, target.Count);
            Console.WriteLine("\n{0} threads each dequeue {1} elements. total time: {2}\n", threadsCount, count, watcher.Elapsed);
            ExecWithStats.OutputStatsSummary(execStats);
        }
        public void SingleThreadTiming()
        {
            const int count = 1000000;
            var target = new ConcurrentPriorityQueue<int>(2);
            var watcher = new Stopwatch();

            watcher.Start();
            for (int i = 0; i < count; i++)
            {
                target.Add(i);
            }
            watcher.Stop();
            Assert.AreEqual(count, target.Count);
            Console.WriteLine("Add {0} elements: {1}", count, watcher.Elapsed);

            watcher.Restart();
            // ReSharper disable once UnusedVariable
            var enumerator = target.GetEnumerator();
            watcher.Stop();
            Console.WriteLine("Get enumerator for {0} elements: {1}", count, watcher.Elapsed);

            watcher.Restart();
            for (int i = 0; i < count; i++)
            {
                target.Take();
            }
            watcher.Stop();
            Assert.AreEqual(0, target.Count);
            Console.WriteLine("Take {0} elements: {1}", count, watcher.Elapsed);

            watcher.Start();
            for (int i = 0; i < 2 * count; i++)
            {
                target.Add(i);
            }
            watcher.Stop();
            Assert.AreEqual(2 * count, target.Count);
            Console.WriteLine("Add twice the capacity of {0} elements: {1}", count, watcher.Elapsed);
        }
Example #39
0
 public StockSimulator()
 {
     BuyQueue = new ConcurrentPriorityQueue<int, int>();
     SellQueue = new ConcurrentPriorityQueue<int, int>();
 }