Strict Priority Queuing
   HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, information, and automation. Computer science spans Theoretical computer science, theoretical disciplines (such as algorithms, theory of computation, and information theory) to Applied science, ...
, a priority queue is an
abstract data type In computer science, an abstract data type (ADT) is a mathematical model for data types, defined by its behavior (semantics) from the point of view of a '' user'' of the data, specifically in terms of possible values, possible operations on data ...
similar to a regular queue or
stack Stack may refer to: Places * Stack Island, an island game reserve in Bass Strait, south-eastern Australia, in Tasmania’s Hunter Island Group * Blue Stack Mountains, in Co. Donegal, Ireland People * Stack (surname) (including a list of people ...
abstract data type. In a priority queue, each element has an associated ''priority'', which determines its order of service. Priority queue serves highest priority items first. Priority values have to be instances of an ordered data type, and higher priority can be given either to the lesser or to the greater values with respect to the given order relation. For example, in
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
standard library, ''PriorityQueues the least elements with respect to the order have the highest priority. This implementation detail is without much practical significance, since passing to the opposite order relation turns the least values into the greatest, and vice versa. While priority queues are often implemented using heaps, they are conceptually distinct. A priority queue can be implemented with a heap or with other methods; just as a list can be implemented with a
linked list In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes whi ...
or with an
array An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
.


Operations

A priority queue has the following operations:


Max-priority queue

* ''insert(S, element, priority)'': add an element to set ''S'' with an associated priority. * ''maximum(S)'': return the element with ''highest priority''. *: This is also known as "''find_max''". * ''extract_max(S)'': remove the element from set ''S'' with ''highest priority'', and return it. *: This is also known as "''delete''", or "''extract''". * ''increase_key(S, element, k)'': increase the associated priority with an element to the new value ''k''.


Min-priority queue

* ''insert(S, element, priority)'': add an element to set ''S'' with an associated priority. * ''minimum(S)'': return the element with ''lowest priority''. *: This is also known as "''find_min''". * ''extract_min(S)'': remove the element from set ''S'' with ''lowest priority'', and return it. *: This is also known as "''delete''", or "''extract''". * ''decrease_key(S, element, k)'': decrease the associated priority with an element to the new value ''k''. Stacks and queues can be implemented as particular kinds of priority queues, with the priority determined by the order in which the elements are inserted. In a stack, the priority of each inserted element is monotonically increasing; thus, the last element inserted is always the first retrieved. In a queue, the priority of each inserted element is monotonically decreasing; thus, the first element inserted is always the first retrieved. In some implementations, if two elements have the same priority, they are served in the same order in which they were enqueued. In other implementations, the order of elements with the same priority is undefined.


Implementation


Naive implementations

One can create a simple, but inefficient priority queue in a number of ways. These naive implementations can demonstrate the expected behaviour of a priority queue in a simpler manner. * ''insert'' elements into an unsorted array; find and ''extract'' element with ''highest priority'' *: Performance: "''insert''" performs in O(1) constant time, where "''extract_max''" performs in O(n) linear time. insert(element, priority): node.element ← element node.priority ← priority list.append(node) extract_max(): highest ← 0 foreach node in list: if highest.priority < node.priority: highest ← node list.remove(highest) return highest.element * ''insert'' elements into a sorted array; ''extract'' first element *: Performance: "''insert''" performs in O(n) linear time, where "''extract_max''" performs in O(1) constant time. insert(element, priority): node.element ← element node.priority ← priority for i in ...N element ← list.get_at_index(i) if element.priority < node.priority: list.insert_at_index(node, i + 1) return extract_max(): highest ← list.get_at_index(0) list.remove(highest) return highest.element


Usual implementation

To improve performance, priority queues are typically based on a heap, giving ''O''(log ''n'') performance for inserts and removals, and ''O''(''n'') to build the heap initially from a set of ''n'' elements. Variants of the basic heap data structure such as pairing heaps or Fibonacci heaps can provide better bounds for some operations. Third edition, p. 518. Alternatively, when a
self-balancing binary search tree In computer science, a self-balancing binary search tree (BST) is any node-based binary search tree that automatically keeps its height (maximal number of levels below the root) small in the face of arbitrary item insertions and deletions.Donald ...
is used, insertion and removal also take ''O''(log ''n'') time, although building trees from existing sequences of elements takes ''O''(''n'' log ''n'') time; this is typical where one might already have access to these data structures, such as with third-party or standard libraries. From a space-complexity standpoint, using
self-balancing binary search tree In computer science, a self-balancing binary search tree (BST) is any node-based binary search tree that automatically keeps its height (maximal number of levels below the root) small in the face of arbitrary item insertions and deletions.Donald ...
with
linked list In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes whi ...
takes more storage, since it requires to store extra references to other nodes. From a computational-complexity standpoint, priority queues are congruent to sorting algorithms. The section on the equivalence of priority queues and sorting algorithms, below, describes how efficient sorting algorithms can create efficient priority queues.


Specialized heaps

There are several specialized heap
data structures In computer science, a data structure is a data organization and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, and the functi ...
that either supply additional operations or outperform heap-based implementations for specific types of keys, specifically integer keys. Suppose the set of possible keys is . * When only ''insert'', ''find-min'' and ''extract-min'' are needed and in case of integer priorities, a bucket queue can be constructed as an array of
linked list In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes whi ...
s plus a pointer , initially . Inserting an item with key appends the item to the 'th list, and updates , both in constant time. ''Extract-min'' deletes and returns one item from the list with index , then increments if needed until it again points to a non-empty list; this takes time in the worst case. These queues are useful for sorting the vertices of a graph by their degree. * A van Emde Boas tree supports the ''minimum'', ''maximum'', ''insert'', ''delete'', ''search'', ''extract-min'', ''extract-max'', ''predecessor'' and ''successor]'' operations in ''O''(log log ''C'') time, but has a space cost for small queues of about ''O''(2''m''/2), where ''m'' is the number of bits in the priority value. The space can be reduced significantly with hashing. * The
Fusion tree In computer science, a fusion tree is a type of tree data structure that implements an associative array on -bit integers on a finite universe, where each of the input integers has size less than 2w and is non-negative. When operating on a collect ...
by Fredman and Willard implements the ''minimum'' operation in ''O''(1) time and ''insert'' and ''extract-min'' operations in O(\log n / \log \log C)time. However it is stated by the author that, "Our algorithms have theoretical interest only; The constant factors involved in the execution times preclude practicality." For applications that do many "
peek Polyether ether ketone (PEEK) is a beige coloured organic thermoplastic polymer in the polyaryletherketone (PAEK) family, used in engineering applications. It was invented in November 1978 and brought to market in the early 1980s by part of I ...
" operations for every "extract-min" operation, the time complexity for peek actions can be reduced to ''O''(1) in all tree and heap implementations by caching the highest priority element after every insertion and removal. For insertion, this adds at most a constant cost, since the newly inserted element is compared only to the previously cached minimum element. For deletion, this at most adds an additional "peek" cost, which is typically cheaper than the deletion cost, so overall time complexity is not significantly impacted.
Monotone priority queue Monotone refers to a sound, for example music or speech, that has a single unvaried tone. See pure tone and monotonic scale. Monotone or monotonicity may also refer to: In economics * Monotone preferences, a property of a consumer's preference ...
s are specialized queues that are optimized for the case where no item is ever inserted that has a lower priority (in the case of min-heap) than any item previously extracted. This restriction is met by several practical applications of priority queues.


Summary of running times


Equivalence of priority queues and sorting algorithms


Using a priority queue to sort

The
semantics Semantics is the study of linguistic Meaning (philosophy), meaning. It examines what meaning is, how words get their meaning, and how the meaning of a complex expression depends on its parts. Part of this process involves the distinction betwee ...
of priority queues naturally suggest a sorting method: insert all the elements to be sorted into a priority queue, and sequentially remove them; they will come out in sorted order. This is actually the procedure used by several
sorting algorithm In computer science, a sorting algorithm is an algorithm that puts elements of a List (computing), list into an Total order, order. The most frequently used orders are numerical order and lexicographical order, and either ascending or descending ...
s, once the layer of
abstraction Abstraction is a process where general rules and concepts are derived from the use and classifying of specific examples, literal (reality, real or Abstract and concrete, concrete) signifiers, first principles, or other methods. "An abstraction" ...
provided by the priority queue is removed. This sorting method is equivalent to the following sorting algorithms:


Using a sorting algorithm to make a priority queue

A sorting algorithm can also be used to implement a priority queue. Specifically, Thorup says:
We present a general deterministic linear space reduction from priority queues to sorting implying that if we can sort up to ''n'' keys in ''S''(''n'') time per key, then there is a priority queue supporting ''delete'' and ''insert'' in ''O''(''S''(''n'')) time and ''find-min'' in constant time.
That is, if there is a sorting algorithm which can sort in ''O''(''S'') time per key, where ''S'' is some function of ''n'' and
word size In computing, a word is any processor design's natural unit of data. A word is a fixed-sized datum handled as a unit by the instruction set or the hardware of the processor. The number of bits or digits in a word (the ''word size'', ''word wid ...
, then one can use the given procedure to create a priority queue where pulling the highest-priority element is ''O''(1) time, and inserting new elements (and deleting elements) is ''O''(''S'') time. For example, if one has an ''O''(''n'' log ''n'') sort algorithm, one can create a priority queue with ''O''(1) pulling and ''O''( log ''n'') insertion.


Libraries

A priority queue is often considered to be a " container data structure". The
Standard Template Library The Standard Template Library (STL) is a software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called ''algorithms'', '' ...
(STL), and the C++ 1998 standard, specifie
std::priority_queue
as one of the STL
container A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping. Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
adaptor class templates. However, it does not specify how two elements with same priority should be served, and indeed, common implementations will not return them according to their order in the queue. It implements a max-priority-queue, and has three parameters: a comparison object for sorting such as a function object (defaults to if unspecified), the underlying container for storing the data structures (defaults to ), and two iterators to the beginning and end of a sequence. Unlike actual STL containers, it does not allow
iteration Iteration is the repetition of a process in order to generate a (possibly unbounded) sequence of outcomes. Each repetition of the process is a single iteration, and the outcome of each iteration is then the starting point of the next iteration. ...
of its elements (it strictly adheres to its abstract data type definition). STL also has utility functions for manipulating another random-access container as a binary max-heap. The
Boost libraries Boost is a set of library (computing), libraries for the C++ programming language that provides support for tasks and structures such as linear algebra, pseudorandom number generator, pseudorandom number generation, multithreading, image proces ...
also have an implementation in the library heap. Python'
heapq
module implements a binary min-heap on top of a list.
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
's library contains a class, which implements a min-priority-queue as a binary heap.
.NET The .NET platform (pronounced as "''dot net"'') is a free and open-source, managed code, managed computer software framework for Microsoft Windows, Windows, Linux, and macOS operating systems. The project is mainly developed by Microsoft emplo ...
's library contains
PriorityQueue
class, which implements an array-backed, quaternary min-heap. Scala's library contains
PriorityQueue
class, which implements a max-priority-queue. Go's library contains
container/heap
module, which implements a min-heap on top of any compatible data structure. The Standard PHP Library extension contains the clas
SplPriorityQueue
Apple's
Core Foundation Core Foundation (also called CF) is a C application programming interface (API) written by Apple Inc. for its operating systems, and is a mix of low-level routines and wrapper functions. Most Core Foundation routines follow a certain naming c ...
framework contains
CFBinaryHeap
structure, which implements a min-heap.


Applications


Bandwidth management

Priority queuing can be used to manage limited resources such as
bandwidth Bandwidth commonly refers to: * Bandwidth (signal processing) or ''analog bandwidth'', ''frequency bandwidth'', or ''radio bandwidth'', a measure of the width of a frequency range * Bandwidth (computing), the rate of data transfer, bit rate or thr ...
on a transmission line from a network router. In the event of outgoing
traffic Traffic is the movement of vehicles and pedestrians along land routes. Traffic laws govern and regulate traffic, while rules of the road include traffic laws and informal rules that may have developed over time to facilitate the orderly an ...
queuing due to insufficient bandwidth, all other queues can be halted to send the traffic from the highest priority queue upon arrival. This ensures that the prioritized traffic (such as real-time traffic, e.g. an RTP stream of a
VoIP Voice over Internet Protocol (VoIP), also known as IP telephony, is a set of technologies used primarily for voice communication sessions over Internet Protocol (IP) networks, such as the Internet. VoIP enables voice calls to be transmitted as ...
connection) is forwarded with the least delay and the least likelihood of being rejected due to a queue reaching its maximum capacity. All other traffic can be handled when the highest priority queue is empty. Another approach used is to send disproportionately more traffic from higher priority queues. Many modern protocols for
local area network A local area network (LAN) is a computer network that interconnects computers within a limited area such as a residence, campus, or building, and has its network equipment and interconnects locally managed. LANs facilitate the distribution of da ...
s also include the concept of priority queues at the
media access control In IEEE 802 LAN/MAN standards, the medium access control (MAC), also called media access control, is the layer that controls the hardware responsible for interaction with the wired (electrical or optical) or wireless transmission medium. Th ...
(MAC) sub-layer to ensure that high-priority applications (such as
VoIP Voice over Internet Protocol (VoIP), also known as IP telephony, is a set of technologies used primarily for voice communication sessions over Internet Protocol (IP) networks, such as the Internet. VoIP enables voice calls to be transmitted as ...
or
IPTV Internet Protocol television (IPTV), also called TV over broadband, is the service delivery of television over Internet Protocol (IP) networks. Usually sold and run by a Telephone company, telecom provider, it consists of broadcast live telev ...
) experience lower latency than other applications which can be served with best-effort service. Examples include
IEEE 802.11e IEEE 802.11e-2005 or 802.11e is an approved amendment to the IEEE 802.11 standard that defines a set of quality of service (QoS) enhancements for wireless Local area network, LAN applications through modifications to the media access control (MA ...
(an amendment to
IEEE 802.11 IEEE 802.11 is part of the IEEE 802 set of local area network (LAN) technical standards, and specifies the set of medium access control (MAC) and physical layer (PHY) protocols for implementing wireless local area network (WLAN) computer com ...
which provides
quality of service Quality of service (QoS) is the description or measurement of the overall performance of a service, such as a telephony or computer network, or a cloud computing service, particularly the performance seen by the users of the network. To quantitat ...
) and
ITU-T The International Telecommunication Union Telecommunication Standardization Sector (ITU-T) is one of the three Sectors (branches) of the International Telecommunication Union (ITU). It is responsible for coordinating Standardization, standards fo ...
G.hn Gigabit Home Networking (G.hn) is a specification for wired home networking that supports speeds up to 2 Gbit/s and operates over four types of legacy wires: telephone wiring, Coaxial cable, coaxial cables, Power line, power lines and pla ...
(a standard for high-speed
local area network A local area network (LAN) is a computer network that interconnects computers within a limited area such as a residence, campus, or building, and has its network equipment and interconnects locally managed. LANs facilitate the distribution of da ...
using existing home wiring ( power lines, phone lines and coaxial cables). Usually a limitation (policer) is set to limit the bandwidth that traffic from the highest priority queue can take, in order to prevent high priority packets from choking off all other traffic. This limit is usually never reached due to high level control instances such as the
Cisco Cisco Systems, Inc. (using the trademark Cisco) is an American multinational digital communications technology conglomerate corporation headquartered in San Jose, California. Cisco develops, manufactures, and sells networking hardware, s ...
Callmanager, which can be programmed to inhibit calls which would exceed the programmed bandwidth limit.


Discrete event simulation

Another use of a priority queue is to manage the events in a
discrete event simulation A discrete-event simulation (DES) models the operation of a system as a (discrete) sequence of events in time. Each event occurs at a particular instant in time and marks a change of state in the system. Between consecutive events, no change in th ...
. The events are added to the queue with their simulation time used as the priority. The execution of the simulation proceeds by repeatedly pulling the top of the queue and executing the event thereon. ''See also'':
Scheduling (computing) In computing, scheduling is the action of assigning resources to perform tasks. The resources may be processors, network links or expansion cards. The tasks may be threads, processes or data flows. The scheduling activity is carried out b ...
,
queueing theory Queueing theory is the mathematical study of waiting lines, or queues. A queueing model is constructed so that queue lengths and waiting time can be predicted. Queueing theory is generally considered a branch of operations research because th ...


Dijkstra's algorithm

When the graph is stored in the form of
adjacency list In graph theory and computer science, an adjacency list is a collection of unordered lists used to represent a finite graph. Each unordered list within an adjacency list describes the set of neighbors of a particular vertex in the graph. This ...
or matrix, priority queue can be used to extract minimum efficiently when implementing
Dijkstra's algorithm Dijkstra's algorithm ( ) is an algorithm for finding the shortest paths between nodes in a weighted graph, which may represent, for example, a road network. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three ...
, although one also needs the ability to alter the priority of a particular vertex in the priority queue efficiently. If instead, a graph is stored as node objects, and priority-node pairs are inserted into a heap, altering the priority of a particular vertex is not necessary if one tracks visited nodes. Once a node is visited, if it comes up in the heap again (having had a lower priority number associated with it earlier), it is popped-off and ignored.


Huffman coding

Huffman coding In computer science and information theory, a Huffman code is a particular type of optimal prefix code that is commonly used for lossless data compression. The process of finding or using such a code is Huffman coding, an algorithm developed by ...
requires one to repeatedly obtain the two lowest-frequency trees. A priority queue is one method of doing this.


Best-first search algorithms

Best-first search Best-first search is a class of search algorithms which explores a graph by expanding the most promising node chosen according to a specified rule. Judea Pearl described best-first search as estimating the promise of node ''n'' by a "heuristic eva ...
algorithms, like the
A* search algorithm A* (pronounced "A-star") is a graph traversal and pathfinding algorithm that is used in many fields of computer science due to its completeness, optimality, and optimal efficiency. Given a weighted graph, a source node and a goal node, the algo ...
, find the shortest path between two vertices or nodes of a
weighted graph This is a glossary of graph theory. Graph theory is the study of graphs, systems of nodes or vertices connected in pairs by lines or edges. Symbols A B ...
, trying out the most promising routes first. A priority queue (also known as the ''fringe'') is used to keep track of unexplored routes; the one for which the estimate (a lower bound in the case of A*) of the total path length is smallest is given highest priority. If memory limitations make best-first search impractical, variants like the
SMA* SMA* or Simplified Memory Bounded A* is a shortest path algorithm based on the A* algorithm. The main advantage of SMA* is that it uses a bounded memory, while the A* algorithm might need exponential memory. All other characteristics of SMA* are ...
algorithm can be used instead, with a
double-ended priority queue In computer science, a double-ended priority queue (DEPQ)ROAM "Roam" is a song by American New wave music, new wave band the B-52's released as the third single from their fifth studio album, ''Cosmic Thing'' (1989). The vocals are sung by Kate Pierson and Cindy Wilson. The B-52's worked with a co-writer, R ...
) algorithm computes a dynamically changing triangulation of a terrain. It works by splitting triangles where more detail is needed and merging them where less detail is needed. The algorithm assigns each triangle in the terrain a priority, usually related to the error decrease if that triangle would be split. The algorithm uses two priority queues, one for triangles that can be split and another for triangles that can be merged. In each step the triangle from the split queue with the highest priority is split, or the triangle from the merge queue with the lowest priority is merged with its neighbours.


Prim's algorithm for minimum spanning tree

Using min heap priority queue in
Prim's algorithm In computer science, Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a Weighted graph, weighted undirected graph. This means it finds a subset of the edge (graph theory), edges that forms a Tree (graph theory), tree ...
to find the
minimum spanning tree A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. ...
of a
connected Connected may refer to: Film and television * ''Connected'' (2008 film), a Hong Kong remake of the American movie ''Cellular'' * '' Connected: An Autoblogography About Love, Death & Technology'', a 2011 documentary film * ''Connected'' (2015 TV ...
and
undirected graph In discrete mathematics, particularly in graph theory, a graph is a structure consisting of a set of objects where some pairs of the objects are in some sense "related". The objects are represented by abstractions called '' vertices'' (also call ...
, one can achieve a good running time. This min heap priority queue uses the min heap data structure which supports operations such as ''insert'', ''minimum'', ''extract-min'', ''decrease-key''. "In order to implement Prim's algorithm efficiently, we need a fast way to select a new edge to add to the tree formed by the edges in A." In this implementation, the
weight In science and engineering, the weight of an object is a quantity associated with the gravitational force exerted on the object by other objects in its environment, although there is some variation and debate as to the exact definition. Some sta ...
of the edges is used to decide the priority of the vertices. Lower the weight, higher the priority and higher the weight, lower the priority.


Parallel priority queue

Parallelization can be used to speed up priority queues, but requires some changes to the priority queue interface. The reason for such changes is that a sequential update usually only has O(1) or O(\log n) cost, and there is no practical gain to parallelize such an operation. One possible change is to allow the concurrent access of multiple processors to the same priority queue. The second possible change is to allow batch operations that work on k elements, instead of just one element. For example, ''extractMin'' will remove the first k elements with the highest priority.


Concurrent parallel access

If the priority queue allows concurrent access, multiple processes can perform operations concurrently on that priority queue. However, this raises two issues. First of all, the definition of the semantics of the individual operations is no longer obvious. For example, if two processes want to extract the element with the highest priority, should they get the same element or different ones? This restricts parallelism on the level of the program using the priority queue. In addition, because multiple processes have access to the same element, this leads to contention. The concurrent access to a priority queue can be implemented on a Concurrent Read, Concurrent Write (CRCW) PRAM model. In the following the priority queue is implemented as a
skip list In computer science, a skip list (or skiplist) is a Randomized algorithm, probabilistic data structure that allows O(\log n) Average-case complexity, average complexity for search as well as O(\log n) average complexity for insertion within an or ...
. In addition, an atomic synchronization primitive, CAS, is used to make the skip list
lock Lock(s) or Locked may refer to: Common meanings *Lock and key, a mechanical device used to secure items of importance *Lock (water navigation), a device for boats to transit between different levels of water, as in a canal Arts and entertainme ...
-free. The nodes of the skip list consists of a unique key, a priority, an
array An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
of
pointers Pointer may refer to: People with the name * Pointer (surname), a surname (including a list of people with the name) * Pointer Williams (born 1974), American former basketball player Arts, entertainment, and media * ''Pointer'' (journal), the ...
, for each level, to the next nodes and a ''delete'' mark. The ''delete'' mark marks if the node is about to be deleted by a process. This ensures that other processes can react to the deletion appropriately. *''insert(e)'': First, a new node with a key and a priority is created. In addition, the node is assigned a number of levels, which dictates the size of the array of pointers. Then a search is performed to find the correct position where to insert the new node. The search starts from the first node and from the highest level. Then the skip list is traversed down to the lowest level until the correct position is found. During the search, for every level the last traversed node will be saved as parent node for the new node at that level. In addition, the node to which the pointer, at that level, of the parent node points towards, will be saved as the successor node of the new node at that level. Afterwards, for every level of the new node, the pointers of the parent node will be set to the new node. Finally, the pointers, for every level, of the new node will be set to the corresponding successor nodes. *''extract-min'': First, the skip list is traversed until a node is reached whose ''delete'' mark is not set. This ''delete'' mark is than set to true for that node. Finally the pointers of the parent nodes of the deleted node are updated. If the concurrent access to a priority queue is allowed, conflicts may arise between two processes. For example, a conflict arises if one process is trying to insert a new node, but at the same time another process is about to delete the predecessor of that node. There is a risk that the new node is added to the skip list, yet it is not longer reachable. ( See image)


''K''-element operations

In this setting, operations on a priority queue is generalized to a batch of k elements. For instance, ''k_extract-min'' deletes the k smallest elements of the priority queue and returns those. In a shared-memory setting, the parallel priority queue can be easily implemented using parallel binary search trees and
join-based tree algorithms In computer science Computer science is the study of computation, information, and automation. Computer science spans Theoretical computer science, theoretical disciplines (such as algorithms, theory of computation, and information theory) ...
. In particular, ''k_extract-min'' corresponds to a ''split'' on the binary search tree that has O(\log n) cost and yields a tree that contains the k smallest elements. ''k_insert'' can be applied by a ''union'' of the original priority queue and the batch of insertions. If the batch is already sorted by the key, ''k_insert'' has O(k\log (1+\frac)) cost. Otherwise, we need to first sort the batch, so the cost will be O(k\log (1+\frac)+k\log k)=O(k\log n). Other operations for priority queue can be applied similarly. For instance, ''k_decrease-key'' can be done by first applying ''difference'' and then ''union'', which first deletes the elements and then inserts them back with the updated keys. All these operations are highly parallel, and the theoretical and practical efficiency can be found in related research papers. The rest of this section discusses a queue-based algorithm on distributed memory. We assume each processor has its own local memory and a local (sequential) priority queue. The elements of the global (parallel) priority queue are distributed across all processors. A ''k_insert'' operation assigns the elements uniformly random to the processors which insert the elements into their local queues. Note that single elements can still be inserted into the queue. Using this strategy the global smallest elements are in the union of the local smallest elements of every processor with high probability. Thus each processor holds a representative part of the global priority queue. This property is used when ''k_extract-min'' is executed, as the smallest m elements of each local queue are removed and collected in a result set. The elements in the result set are still associated with their original processor. The number of elements m that is removed from each local queue depends on k and the number of processors p. By parallel selection the k smallest elements of the result set are determined. With high probability these are the global k smallest elements. If not, m elements are again removed from each local queue and put into the result set. This is done until the global k smallest elements are in the result set. Now these k elements can be returned. All other elements of the result set are inserted back into their local queues. The running time of ''k_extract-min'' is expected O(\frac \log(n)) , where k = \Omega(p \cdot \log (p)) and n is the size of the priority queue. The priority queue can be further improved by not moving the remaining elements of the result set directly back into the local queues after a ''k_extract-min'' operation. This saves moving elements back and forth all the time between the result set and the local queues. By removing several elements at once a considerable speedup can be reached. But not all algorithms can use this kind of priority queue. Dijkstra's algorithm for example can not work on several nodes at once. The algorithm takes the node with the smallest distance from the priority queue and calculates new distances for all its neighbor nodes. If you would take out k nodes, working at one node could change the distance of another one of the k nodes. So using k-element operations destroys the label setting property of Dijkstra's algorithm.


See also

* Batch queue * Command queue *
Job scheduler A job scheduler is a computer application for controlling unattended background program execution of jobs. This is commonly called batch scheduling, as execution of non-interactive jobs is often called batch processing, though traditional ''job ...


References


Further reading

*


External links


C++ reference for std::priority_queue

Descriptions
by Lee Killough
libpqueue
is a generic priority queue (heap) implementation (in C) used by the Apache HTTP Server project.

by Stefan Xenos
UC Berkeley - Computer Science 61B - Lecture 24: Priority Queues
(video) - introduction to priority queues using binary heap {{Data structures Abstract data types