Example #1
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 #2
0
        /// <summary>
        ///     Enqueue a message
        /// </summary>
        /// <param name="message">message to enqueue</param>
        /// <remarks>
        ///     <para>
        ///         Messages do not have to be placed in order, place them as they should be sent out.
        ///     </para>
        /// </remarks>
        public void Enqueue(object message)
        {
            var response = message as IHttpMessage;

            if (response == null)
            {
                _queue.Enqueue(++_lastIndex, message);
                return;
            }

            var header = response.Headers[HttpMessage.PipelineIndexKey];

            if (header == null)
            {
                throw new InvalidOperationException("PipelinedMessageQueue requires the header '" +
                                                    HttpMessage.PipelineIndexKey +
                                                    "' to support HTTP pipelinging.");
            }

            var value = 0;

            if (!int.TryParse(header, out value))
            {
                throw new InvalidOperationException("PipelinedMessageQueue require the header '" +
                                                    HttpMessage.PipelineIndexKey +
                                                    "' and that it contains a numerical value.");
            }

            _lastIndex = value;
            _queue.Enqueue(value, response);
        }
        void RequestUpdateBuffer(ChunkVertexBuilder vertexBuilder, ChunkMeshUpdatePriority priority)
        {
            for (int z = 0; z < MeshSegments.Z; z++)
            {
                for (int y = 0; y < MeshSegments.Y; y++)
                {
                    for (int x = 0; x < MeshSegments.X; x++)
                    {
                        var opaqueRequest = new UpdateBufferRequest
                        {
                            VertexBuilder = vertexBuilder,
                            Segment       = new IntVector3(x, y, z),
                            Translucece   = false,
                            Priority      = priority,
                            RequestTime   = TimeSpan.FromTicks(Environment.TickCount)
                        };
                        updateBufferRequests.Enqueue(opaqueRequest);

                        var translucentRequest = new UpdateBufferRequest
                        {
                            VertexBuilder = vertexBuilder,
                            Segment       = new IntVector3(x, y, z),
                            Translucece   = true,
                            Priority      = priority,
                            RequestTime   = TimeSpan.FromTicks(Environment.TickCount)
                        };
                        updateBufferRequests.Enqueue(translucentRequest);
                    }
                }
            }
        }
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 ExecuteCommandAsync(Command command, EventHandler <CommandExecutedEventArgs> callback)
        {
            lock (queue)
                queue.Enqueue(new KeyValuePair <Command, EventHandler <CommandExecutedEventArgs> >(command, callback), 5);

            resetEvent.Set();
        }
Example #6
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);
            }
        }
        /// <summary>
        /// Update loop. Get the work from the leve management queue and activate chunks and meshes
        /// </summary>
        void Update()
        {
            if (!isLoaded)
            {
                return;
            }

            // first schedule all jobs that are ready from the levelManager thread
            runReadyJobs();
            // check for jobs that finished running
            checkForFinishedJobs();

            // NOTE:: Newly activated chunks goes first so we don't mesh then activate in the same frame
            /// go through the chunk activation queue and activate chunks
            if (chunksToActivate.TryDequeue(out KeyValuePair <float, Coordinate> chunkToActivate))
            {
                // if the chunk doesn't have a meshed and baked controller yet, we can't activate it, so wait.
                if (!tryToGetAssignedChunkController(chunkToActivate.Value, out ChunkController assignedController) || // has a controller
                    !(assignedController.isActive && assignedController.isMeshed) || // is active and meshed
                    !assignedController.checkColliderIsBaked() // colliders are baked
                    )
                {
                    chunksToActivate.Enqueue(chunkToActivate);
                }
                else
                {
                    assignedController.enableObjectVisible();
                }
            }

            /// try to assign newly mehsed chunks that are waiting on controllers, if we run out.
            if (chunkMeshesWaitingForAFreeController.TryDequeue(out KeyValuePair <float, VoxelMeshData> chunkMeshWaitingForController))
            {
                if (!tryToAssignNewlyMeshedChunkToController(chunkMeshWaitingForController.Value))
                {
                    chunkMeshesWaitingForAFreeController.Enqueue(chunkMeshWaitingForController);
                }
            }

            /// try to assign meshes to the chunks with newly generated meshes
            if (chunksToMesh.TryDequeue(out KeyValuePair <float, ChunkController> chunkToMesh))
            {
                chunkToMesh.Value.updateMeshWithChunkData();
            }

            /// try to remove meshes for the given chunk and reset it's mesh data
            if (chunksToDeMesh.TryDequeue(out KeyValuePair <float, ChunkController> chunkToDemesh))
            {
                chunkToDemesh.Value.deactivateAndClear();
            }

            /// go through the de-activation queue
            if (chunksToDeactivate.TryDequeue(out KeyValuePair <float, Coordinate> deactivatedChunkLocation))
            {
                if (tryToGetAssignedChunkController(deactivatedChunkLocation.Value, out ChunkController assignedController))
                {
                    assignedController.disableObjectVisible();
                }
            }
        }
Example #8
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 #9
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 #10
0
 /// <summary>
 /// Request texture loading
 /// </summary>
 /// <param name="address"></param>
 public void RequestTile(VTAddress address)
 {
                 #if USE_PRIORITY_QUEUE
     requestQueue.Enqueue(address.MipLevel, address);
                 #else
     requestQueue.Enqueue(address);
                 #endif
 }
        /// <summary>
        /// Initilize the level queue manager to follow the foci and appetures of the level
        /// </summary>
        /// <param name="level"></param>
        public void initializeFor(Level level)
        {
            if (chunkObjectPrefab == null)
            {
                World.Debugger.logError("UnityLevelController Missing chunk prefab, can't work");
            }
            else if (level == null)
            {
                World.Debugger.logError("No level provided to level controller");
            }
            else
            {
                /// init
                this.level = level;

                // build the controller pool based on the maxed meshed chunk area we should ever have:
                ChunkResolutionAperture meshResolutionAperture = level.getApetureByPriority(Level.AperturePriority.Meshed);
                int diameterToMeshManager = meshResolutionAperture != null ? meshResolutionAperture.managedChunkRadius : level.chunkBounds.x;
                chunkControllerPool = new ChunkController[diameterToMeshManager * diameterToMeshManager * level.chunkBounds.y * 2];
                for (int index = 0; index < chunkControllerPool.Length; index++)
                {
                    // for each chunk we want to be able to render at once, create a new pooled gameobject for it with the prefab that has a unitu chunk controller on it
                    GameObject chunkObject = Instantiate(chunkObjectPrefab);
                    chunkObject.transform.parent = gameObject.transform;
                    ChunkController chunkController = chunkObject.GetComponent <ChunkController>();
                    if (chunkController == null)
                    {
                        World.Debugger.logError($"No chunk controller on {chunkObject.name}");
                    }
                    else
                    {
                        chunkControllerPool[index]   = chunkController;
                        chunkController.levelManager = this;
                        chunkObject.SetActive(false);
                    }
                }

                /// this controller is now loaded
                isLoaded = true;

                /// add the focus initilization jobs to the queue for each apeture
                level.forEachFocus(focus => {
                    level.forEachAperture(aperture => {
                        foreach (ChunkResolutionAperture.ApetureChunkAdjustment chunkAdjustment in aperture.getAdjustmentsForFocusInitilization(focus))
                        {
                            apertureJobQueue.Enqueue(getCurrentPriorityForChunk(chunkAdjustment.chunkID, aperture), chunkAdjustment);
                        }
                    });
                });

                /// start the manager job in a seperate thread
                apertureJobQueueManagerThread = new Thread(() => ManageQueue())
                {
                    Name = "Level Aperture Queue Manager"
                };
                apertureJobQueueManagerThread.Start();
            }
        }
        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 #13
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);
        }
Example #14
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));
        }
Example #15
0
        Enqueue(double priority, WaitCallback callback, object context = null)
        {
            if (IsStopping)
            {
                // We want to block new tasks from being queued while the task runner is trying to
                // shut down, so that it can successfully stop instead of being bogged down by new
                // tasks forever.
                throw new InvalidOperationException("Cannot enqueue tasks while the task runner is stopping.");
            }

            // Create a new task, wrap it in a PriorityValuePair, and enqueue it.
            Task task = new Task(context, callback);
            PriorityValuePair <Task> elem = new PriorityValuePair <Task>(priority, task);

            __queue.Enqueue(elem);

            // Mark the task as waiting to complete.
            onWaitingTask(elem);

            // Subscribe an event listener to the task's CallbackReturned event that will release
            // the task resources and allow another to run.
            ManualResetEvent resetEvent = new ManualResetEvent(false);

            task.TaskComplete += delegate {
                onCompletedTask(elem);
                resetEvent.Set();
            };

            // Return the ManualResetEvent to the caller so they can be aware of when this task
            // finishes execution.
            return(resetEvent);
        }
Example #16
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;
        }
Example #17
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 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));
        }
        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 #20
0
        internal void Enqueue(Action <Camera> queueAction, Camera camera, PriorityValue priority)
        {
            _queue.Enqueue(new ActionInfo(queueAction, true, _dispatcher, camera), new Priority(priority));

            if (_queue.Count > 1)
            {
                return;
            }

            ActionInfo result = null;

            result = _queue.Peek();
            //_queue.TryPeek(out result);
            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 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 #22
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 #23
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));
        }
        public void RequestTask(Chunk chunk, ChunkTaskType taskType, ChunkTaskPriority priority)
        {
            var request = requestPool.Borrow();

            request.Initialize(chunk, taskType, priority);

            requests.Enqueue(request);
        }
Example #25
0
        private void QueryProcess()
        {
            //if (m_dblog)
            //{
            //    m_LogWriterExt =
            //        new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "DbLogs" + Path.DirectorySeparatorChar
            //                         + m_Name + "_" + DateTime.Now.ToString("yyyy-MM-dd") + "_ext.log", true);
            //}
            Action <DataSet> null_action = (ds) => { };

            m_Logger.Info("{0} thread start", Thread.CurrentThread.Name);
            while (Status == DbStatus.Running)
            {
                Interlocked.Increment(ref m_CallingItemsCount);
                KeyValuePair <DateTime, DBReadItem> item;
                if (m_QueryWorkItems.TryDequeue(out item))
                {
                    Action <DataSet> callback = item.Value.CallBack != null ? item.Value.CallBack : null_action;

                    DataSet ds = null;
                    Performance.Record(
                        item.Value.SQL,
                        item.Value.GroupName,
                        () =>
                    {
                        try
                        {
                            ds = m_Provider.Query(m_QueryConnString, item.Value.SQL);
                        }
                        catch (Exception ex)
                        {
                            m_Logger.Error(item.Value.SQL + Environment.NewLine, ex);
                        }
                    },
                        MonitoringType.DBExcute);
                    m_CallBackItems.Enqueue(item.Key, new DBCallBackItem()
                    {
                        GroupName = item.Value.GroupName, CallBack = callback, Data = ds, Name = item.Value.SQL
                    });

                    Interlocked.Increment(ref m_QueriedItemsCount);
                    Interlocked.Decrement(ref m_CallingItemsCount);
                }
                else
                {
                    Interlocked.Decrement(ref m_CallingItemsCount);
                    Thread.Sleep(IDLE_SLEEP_MILISECONDS);
                }
            }

            if (m_LogWriterExt != null)
            {
                m_LogWriterExt.Close();
                m_LogWriterExt = null;
            }
            Log.InfoFormat("{0} query thread stop", Thread.CurrentThread.Name);
        }
        ///// PUBLIC FUNCTIONS

        /// <summary>
        /// Add a bunch of objects to the queue for processing
        /// </summary>
        /// <param name="queueItems"></param>
        /// <param name="sortQueue">whether or not to sort the queue on add.</param>
        public void enqueue(QueueItemType[] queueItems)
        {
            foreach (QueueItemType queueItem in queueItems)
            {
                queue.Enqueue(getPriorityAndPackageItem(queueItem));
                // if the chunk was canceled in the past, remove the cancelation token when we add it back
                if (canceledItems.TryGetValue(queueItem, out _))
                {
                    canceledItems.TryRemove(queueItem, out _);
                }
            }

            // if the queue manager job isn't running, start it
            if (!isRunning)
            {
                start();
            }
        }
Example #27
0
        public void Clear()
        {
            // 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);

            // Ensure that 3 elements have been added to the queue.
            Assert.That(queue.Count, Is.EqualTo(3));

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

            // Ensure that all of the elements have been removed.
            Assert.That(queue.Count, Is.EqualTo(0));
        }
Example #28
0
        public void AddToOrderedChannel(Packet message)
        {
            try
            {
                if (_cancellationToken.Token.IsCancellationRequested)
                {
                    return;
                }

                if (message.ReliabilityHeader.OrderingIndex <= _lastOrderingIndex)
                {
                    return;
                }

                lock (_eventSync)
                {
                    //Log.Debug($"Received packet {message.Id} with ordering index={message.ReliabilityHeader.OrderingIndex}. Current index={_lastOrderingIndex}");

                    //if (_orderingBufferQueue.Count == 0 && message.ReliabilityHeader.OrderingIndex == _lastOrderingIndex + 1)
                    //{
                    //	if (_orderedQueueProcessingThread != null)
                    //	{
                    //		// Remove the thread again? But need to deal with cancellation token, so not entirely easy.
                    //		// Needs refactoring of the processing thread first.
                    //	}
                    //	_lastOrderingIndex = message.ReliabilityHeader.OrderingIndex;
                    //	HandlePacket(message);
                    //	return;
                    //}

                    if (_orderedQueueProcessingThread == null)
                    {
                        _orderedQueueProcessingThread = new Thread(ProcessOrderedQueue)
                        {
                            IsBackground = true,
                            Name         = $"Ordering Thread [{EndPoint}]"
                        };
                        _orderedQueueProcessingThread.Start();
                        if (Log.IsDebugEnabled)
                        {
                            Log.Warn($"Started processing thread for {Username}");
                        }
                    }

                    _orderingBufferQueue.Enqueue(message.ReliabilityHeader.OrderingIndex, message);
                    if (message.ReliabilityHeader.OrderingIndex == _lastOrderingIndex + 1)
                    {
                        WaitHandle.SignalAndWait(_packetQueuedWaitEvent, _packetHandledWaitEvent);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
Example #29
0
        public void EnqueuePriorityValue()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

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

            // Store an element and insert it into the queue.
            queue.Enqueue(1.0, 2);

            // Ensure that the element was inserted into the queue.
            Assert.That(queue.Peek().Value, Is.EqualTo(2));

            // Store another element with higher priority and insert it as well.
            queue.Enqueue(2.0, 4);

            // Ensure that the element was inserted into the queue.
            Assert.That(queue.Peek().Value, Is.EqualTo(4));
        }
        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);
        }
        // メッシュ更新は2フェーズ。
        // 1. 非同期な頂点構築
        // 2. 構築された頂点による同期バッファ更新。
        //
        // 恐らく、バッファ更新は GPU との同期が発生するため、
        // 非同期ではなくゲーム スレッドで実行すべきであろうと思われる。

        public void RequestUpdateMesh(Chunk chunk, ChunkMeshUpdatePriority priority)
        {
            if (chunk == null)
            {
                throw new ArgumentNullException("chunk");
            }

            var request = buildVertexRequestPool.Borrow();

            request.Initialize(chunk, priority);

            buildVertexRequests.Enqueue(request);
        }