Esempio n. 1
0
        internal void Dequeue()
        {
            if (_queue.Count <= 0)
            {
                return;
            }

            ActionInfo result = null;

            result = _queue.Dequeue();
            if (result == null)
            {
                return;
            }

            if (_queue.Count <= 0)
            {
                return;
            }

            result = _queue.Peek();
            if (result != null)
            {
                _queue.UpdatePriority(result, new Priority(PriorityValue.Critical));
                try
                {
                    result.Exec();
                }
                catch (Exception e)
                {
                    Debug.WriteLine("message: {0}; stacktrace: {1}", e.Message, e.StackTrace);
                }
            }
        }
        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);
        }
        public void DequeueWithTooBigCapacity()
        {
            var target = new ConcurrentPriorityQueue <string, int>(50);

            for (var i = 0; i < 13; i++)
            {
                target.Enqueue("a", i);
            }
            Assert.AreEqual(50, target.Capacity);
            Assert.AreEqual(13, target.Count);
            target.Dequeue();
            Assert.AreEqual(25, target.Capacity);
            Assert.AreEqual(12, target.Count);
            target.Dequeue();
            Assert.AreEqual(25, target.Capacity);
            Assert.AreEqual(11, target.Count);
        }
Esempio n. 4
0
        ThreadProc()
        {
            // Change state to indicate that the task runner is started.
            __state = TaskRunnerState.Running;

            // Emit an event to notify listeners that the task runner started up.
            if (Started != null)
            {
                Started();
            }

            // Continue looping until Stop() is called and all critical tasks are finished.
            while (!IsStopping || IsStopping && HasEnqueuedCriticalTasks)
            {
                // Most of this is only important if something is in the queue.
                if (RunningTasks < ThreadPoolMaxThreads && __queue.Peek() != null)
                {
                    // Execute the task on the thread pool.
                    PriorityValuePair <Task> elem = __queue.Dequeue();
                    Task task = elem.Value;
                    if (task != null)
                    {
                        // We're passing a null context here because the task is packaged with its
                        // own execution context that will be inserted during Task.Run().
                        ThreadPool.QueueUserWorkItem((x) => { task.Run(); }, null);
                    }

                    // Mark the task as starting execution.
                    // Note: This should run even if the task is null above, otherwise the counts
                    // for the number of running/waiting tasks will become skewed.
                    onRunningTask(elem);
                }
                else
                {
                    // Yield the rest of the time slice.
                    Thread.Sleep(1);
                }
            }

            // Wait for all critical tasks to finish running before stopping.
            while (HasWaitingCriticalTasks)
            {
                Thread.Sleep(1);
            }

            // Flag the task runner as stopped.
            __state  = TaskRunnerState.Stopped;
            __thread = null;

            // Emit an event to notify listeners that the task runner stopped.
            if (Stopped != null)
            {
                Stopped();
            }
        }
        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());
        }
Esempio n. 6
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));
        }
Esempio n. 7
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);
        }
Esempio n. 8
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));
        }
Esempio n. 9
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);
        }
Esempio n. 11
0
        // Scan and fetches best icon per Options.
        public Image ScanAndFetch()
        {
            var parsedUris = new HashSet <Uri>();

            foreach (var possibleIcon in new Scanner(Source).Scan(TargetUri))
            {
                // Because the scanner can return duplicate URIs.
                if (parsedUris.Contains(possibleIcon.Location))
                {
                    continue;
                }
                parsedUris.Add(possibleIcon.Location);

                // Hopefully we've already found it
                if (_IsPerfect(possibleIcon.ExpectedSize))
                {
                    var image = DownloadImages_ReturnPerfect(possibleIcon.Location);
                    if (image != null)
                    {
                        return(image);
                    }
                }

                // If not, we'll look at it later.
                else
                {
                    notVerified.Enqueue(possibleIcon, -1 * _GetDistance(possibleIcon.ExpectedSize));
                }
            }

            // Download them, prioritizing those closest to perfect
            foreach (var possibleIcon in notVerified)
            {
                var image = DownloadImages_ReturnPerfect(possibleIcon.Location);
                if (image != null)
                {
                    return(image);
                }
            }

            // Since none were a perfect match, just return the closest
            if (downloadedImages.Count == 0)
            {
                return(null);
            }
            return(downloadedImages.Dequeue());
        }
Esempio n. 12
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));
        }
Esempio n. 13
0
            public string Allocate(int startTick, int duration)
            {
                if (startTick < lastStartTick)
                {
                    throw new InvalidOperationException("startTick must not be less than last called value.");
                }
                while (UsedIdentifiers.Count > 0 && UsedIdentifiers.Peek().Item1 < startTick)
                {
                    IdentifierStack.Push(UsedIdentifiers.Dequeue().Item2);
                }
                string s       = IdentifierStack.Pop();
                int    endTick = startTick + duration;

                UsedIdentifiers.Enqueue(Tuple.Create(endTick, s), -endTick);
                lastStartTick = startTick;
                return(s);
            }
        public void SingleThreadTiming()
        {
            const int count   = 1000000;
            var       target  = new ConcurrentPriorityQueue <string, int>(2);
            var       watcher = new Stopwatch();

            watcher.Start();
            for (int i = 0; i < count; i++)
            {
                target.Enqueue("a", 1);
            }
            watcher.Stop();
            Assert.AreEqual(count, target.Count);
            Console.WriteLine("Enqueue {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.Dequeue();
            }
            watcher.Stop();
            Assert.AreEqual(0, target.Count);
            Console.WriteLine("Dequeue {0} elements: {1}", count, watcher.Elapsed);

            watcher.Start();
            for (int i = 0; i < 2 * count; i++)
            {
                target.Enqueue("a", 1);
            }
            watcher.Stop();
            Assert.AreEqual(2 * count, target.Count);
            Console.WriteLine("Enqueue twice the capacity of {0} elements: {1}", count, watcher.Elapsed);
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            ConcurrentPriorityQueue <string> queue = new ConcurrentPriorityQueue <string>();

            queue.Enqueue(1000.0, "This ");
            queue.Enqueue(1000.0, "should ");
            queue.Enqueue(1000.0, "form ");
            queue.Enqueue(1000.0, "a ");
            queue.Enqueue(1000.0, "complete ");
            queue.Enqueue(1000.0, "and ");
            queue.Enqueue(1000.0, "understandable ");
            queue.Enqueue(1000.0, "sentence.");

            int numIterations = queue.Count;

            for (int x = 0; x < numIterations; x++)
            {
                Console.WriteLine("ITERATION " + (x + 1));
                Console.WriteLine("");

                // Print out the current state of the heap
                PriorityValuePair <string>[] heapArray = new PriorityValuePair <string> [queue.Count];
                queue.CopyTo(heapArray, 0);
                for (int i = 0; i < heapArray.Length; i++)
                {
                    Console.WriteLine(heapArray[i].Value + ", " + heapArray[i].Priority);
                }

                // Dequeue the next element
                PriorityValuePair <string> dequeued = queue.Dequeue();
                Console.WriteLine("");
                Console.WriteLine("DEQUEUED: " + dequeued.Value + ", " + dequeued.Priority);
                Console.WriteLine("");
            }

            Console.ReadLine();
        }
Esempio n. 16
0
        private void ExecuteCommandWorker()
        {
            try
            {
                while (true)
                {
                    if (queue.Count > 0)
                    {
                        KeyValuePair <Command, EventHandler <CommandExecutedEventArgs> > entry;
                        lock (queue)
                            entry = queue.Dequeue();

                        try
                        {
                            RconPacket request  = new RconPacket(PacketType.ServerdataExeccommand, entry.Key.ToString());
                            RconPacket response = rcon.SendReceive(request);

                            if (request.Id != response.Id)
                            {
                                throw new Exception("Got a response with a wrong ID!");
                            }

                            var commandExecutedEventArgs = new CommandExecutedEventArgs()
                            {
                                Successful = response != null,
                                Error      = "",
                                Response   = response?.Body.Trim(),
                                Command    = entry.Key
                            };
                            entry.Value?.Invoke(this, commandExecutedEventArgs);
                            CommandExecuted?.Invoke(this, commandExecutedEventArgs);
                        }
                        catch (SocketException sEx)
                        {
                            Disconnect(false);

                            var commandExecutedEventArgs = new CommandExecutedEventArgs()
                            {
                                Successful = false,
                                Error      = sEx.Message,
                                Response   = "",
                                Command    = entry.Key
                            };
                            entry.Value?.Invoke(this, commandExecutedEventArgs);
                            CommandExecuted?.Invoke(this, commandExecutedEventArgs);
                        }
                        catch (Exception ex)
                        {
                            var commandExecutedEventArgs = new CommandExecutedEventArgs()
                            {
                                Successful = false,
                                Error      = ex.Message,
                                Response   = "",
                                Command    = entry.Key
                            };
                            entry.Value?.Invoke(this, commandExecutedEventArgs);
                            CommandExecuted?.Invoke(this, commandExecutedEventArgs);
                        }
                    }

                    if (queue.Count == 0)
                    {
                        resetEvent.Reset();
                    }

                    resetEvent.WaitOne();
                }
            }
            catch (ThreadAbortException tEx)
            {
            }
        }
        public void MultiThreadEnqueue()
        {
            const int capacity     = 1000000;
            const int threadsCount = 100;
            const int count        = capacity / threadsCount;
            var       target       = new ConcurrentPriorityQueue <string, 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("Enqueue {0}", count), count, () => target.Enqueue("a", 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("Dequeue {0}", count), count, () => target.Dequeue());
                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 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);
            //}
        }
Esempio n. 19
0
        public Stack <Tile> FindPath(bool includeLast)
        {
            if (_startTile == null || _endTile == null)
            {
                return(null);
            }

            if (_startTile.Region != _endTile.Region &&
                !RegionTileNextTo(_startTile, _endTile))
            {
                return(null);
            }

            if (_startTile == _endTile)
            {
                var newStack = new Stack <Tile>();
                newStack.Push(_endTile);
                return(newStack);
            }

            _openList.Enqueue(_startTile, 0);
            _fScores[_startTile] = 0;

            do
            {
                var bestFScoreTile = _openList.Dequeue();
                _closedList.Add(bestFScoreTile);

                var neighbors = bestFScoreTile.GetNeighbors();

                if (bestFScoreTile == _endTile)
                {
                    return(ConstructPath(includeLast));
                }

                foreach (var neighbor in neighbors)
                {
                    if (neighbor == null)
                    {
                        continue;
                    }
                    if (neighbor.MovementCost == 0 && neighbor != _endTile)
                    {
                        continue;
                    }
                    if (_closedList.Contains(neighbor))
                    {
                        continue;
                    }
                    if (CanMoveToNeighbour(neighbor, neighbors) == false)
                    {
                        continue;
                    }

                    int fScore = _fScores[bestFScoreTile] + Cost(bestFScoreTile, neighbor);

                    if (!_openList.Contains(neighbor) || fScore < _fScores[neighbor])
                    {
                        _fScores[neighbor]  = fScore;
                        _cameFrom[neighbor] = bestFScoreTile;
                        var priority = (int)(fScore + Heuristic(neighbor, _endTile));
                        _openList.Enqueue(neighbor, -priority);
                    }
                }
            } while (_openList.Count > 0);

            return(null);
        }