Skip to main content

ConcurrentPriorityQueue

Struct ConcurrentPriorityQueue 

Source
pub struct ConcurrentPriorityQueue<K, P, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> { /* private fields */ }
Available on crate feature concurrent only.
Expand description

A concurrent indexed max-priority queue with relaxed and exact removal.

Each shard wraps a PagedPriorityQueue. The key’s index page determines its shard, keeping all generations of a slot together and allocating that index page in just one shard. PAGE must be nonzero. Workloads with fewer key pages than shards can distribute entries unevenly and reduce the effectiveness of relaxed popping. D selects the plain queue’s directory. Each shard can hold at most u32::MAX entries.

pop returns the greatest of up to two sampled shard tops, with a fallback scan for nonempty shards. It has no rank guarantee with multiple shards. A key present throughout the call, with its insertion happening-before the call, prevents None. pop_exact and peek_exact select the global maximum. Ties have unspecified order.

§Locking and panics

Per-key operations lock one shard. Operations holding several shard locks at once acquire them in ascending shard order. Callbacks and user trait implementations such as Ord, Clone, Debug and Serialize run under shard locks and must avoid calling back into this queue, which can deadlock even on reads. The spin lock used without std permits writer starvation.

Locks ignore poisoning. If a priority comparison or a mutation callback panics, mutations already made remain in effect and all remaining entries stay findable with their priorities. Heap order may be broken in the modified shard, so subsequent maximum results may be unspecified. See PagedPriorityQueue for its panic guarantees.

use paged_collections::concurrent::ConcurrentPriorityQueue;

let queue = ConcurrentPriorityQueue::<u32, i32, 4>::with_shards(3);
assert_eq!(queue.push(1, 10), None);
assert_eq!(queue.push(5, 20), None);
assert_eq!(queue.change_priority(&1, 30), Some(10));
assert_eq!(queue.pop_exact(), Some((1, 30)));
assert_eq!(queue.pop(), Some((5, 20)));
assert_eq!(queue.pop(), None);

Implementations§

Source§

impl<K: Key, P, const PAGE: usize, D: Directory> ConcurrentPriorityQueue<K, P, PAGE, D>

Source

pub fn new() -> Self

Creates an empty queue with the default shard count.

With std, the count is four times the available parallelism, capped at 256, or four if parallelism is unknown. Without std it is eight.

§Panics

Panics if PAGE is zero.

Source

pub fn with_shards(shards: usize) -> Self

Creates an empty queue with shards shards.

§Panics

Panics if shards or PAGE is zero.

Source

pub fn with_shards_and_capacity(shards: usize, capacity: usize) -> Self

Creates an empty queue with dense capacity distributed across shards shards, rounding up per shard. Index pages are allocated on demand.

§Panics

Panics if shards or PAGE is zero, or the capacity cannot be allocated.

Source

pub fn shards(&self) -> usize

Returns the number of shards.

Source

pub fn len(&self) -> usize

Returns the sum of shard lengths, exact when no write is in flight.

Source

pub fn is_empty(&self) -> bool

Returns whether the length hints report an empty queue.

Like len, this is exact when no write is in flight.

Source

pub fn allocated_pages(&self) -> usize

Returns the total number of allocated index pages, reading one shard at a time. The total is weakly consistent across shards.

Source

pub fn contains_key(&self, key: &K) -> bool

Looks up the exact key, including its generation, under a read lock.

Source

pub fn priority(&self, key: &K) -> Option<P>
where P: Clone,

Clones the exact key’s priority under a read lock, or returns None if absent. The clone must avoid calling back into this queue.

Source

pub fn with_priority<R>(&self, key: &K, f: impl FnOnce(&P) -> R) -> Option<R>

Calls f with the exact key’s priority under a read lock.

Returns None without calling f if absent. The callback must avoid calling back into this queue.

Source

pub fn clear(&mut self)

Removes all entries, retaining index pages and dense capacity.

Source

pub fn shrink_to_fit(&mut self)

Shrinks the dense arrays and directories, freeing index pages of empty shards.

Source

pub fn drain(&mut self) -> IntoIter<(K, P)> ⓘ

Eagerly removes all entries and returns them in arbitrary order.

Index pages and dense capacity stay allocated. Dropping the iterator drops its remaining entries.

Source§

impl<K: Key, P: Ord, const PAGE: usize, D: Directory> ConcurrentPriorityQueue<K, P, PAGE, D>

Source

pub fn push(&self, key: K, priority: P) -> Option<P>

Inserts a key or updates its priority under one shard write lock.

Returns the previous priority of the same key, keeping the stored key. Another generation occupying the slot is evicted and yields None.

Source

pub fn try_push(&self, key: K, priority: P) -> Result<Option<P>, (K, P)>

Inserts or updates under one shard write lock, refusing an occupied slot held by another generation.

Returns the previous priority on update, or the supplied pair on refusal.

Source

pub fn replace(&self, key: K, priority: P) -> Option<(K, P)>

Stores the supplied key and priority under one shard write lock.

Returns the former occupant of the slot, including an evicted generation or an equal key.

Source

pub fn push_increase(&self, key: K, priority: P) -> bool

Inserts an absent key or raises its priority if strictly greater, returning whether the queue changed. An absent generation evicts the slot’s occupant as in push.

Source

pub fn push_decrease(&self, key: K, priority: P) -> bool

Inserts an absent key or lowers its priority if strictly smaller, returning whether the queue changed. An absent generation evicts the slot’s occupant as in push.

Source

pub fn change_priority(&self, key: &K, priority: P) -> Option<P>

Changes the priority of the exact key under a write lock, returning its previous priority or None if absent.

Source

pub fn change_priority_with(&self, key: &K, change: impl FnOnce(&mut P)) -> bool

Mutates the exact key’s priority under a write lock and repairs heap order. Returns whether the key was present.

The callback runs only for a present key and must avoid calling back into this queue. If it panics, its changes remain and heap order may be broken.

Source

pub fn remove(&self, key: &K) -> Option<(K, P)>

Removes and returns the stored pair for the exact key, or None if absent, under one shard write lock.

Source

pub fn pop(&self) -> Option<(K, P)>

Removes an entry using relaxed priority ordering.

Samples two distinct shards, preferring nonzero length hints. Locks both in ascending shard order and removes the greater top. If both are empty, visits every shard once from a random start, locking one at a time, and removes the first top it finds.

With one shard this removes the maximum. With multiple shards there is no rank guarantee. Rihani, Sanders and Dementiev (2015) report empirical expected rank O(shards) for MultiQueues.

Returns None only if every shard was empty when visited. An entry present throughout the call, with its insertion happening-before the call, therefore prevents None because entries never migrate.

Source

pub fn pop_exact(&self) -> Option<(K, P)>

Removes the global maximum, or returns None if empty.

Acquires all shard write locks in ascending order. This operation is linearizable.

Source

pub fn peek_exact(&self) -> Option<(K, P)>
where P: Clone,

Copies the key and clones the priority of the global maximum, or returns None if empty.

Acquires all shard read locks in ascending order for a linearizable view. The priority’s Clone must avoid calling back into this queue.

Source

pub fn into_sorted_vec(self) -> Vec<(K, P)>

Consumes the queue into entries in ascending priority order.

Source

pub fn into_queue(self) -> PagedPriorityQueue<K, P, PAGE, D>

Consumes the queue and merges its entries into one plain queue.

§Panics

Panics if the entries exceed the plain queue’s u32::MAX limit or if comparing priorities panics.

Source

pub fn snapshot(&self) -> PagedPriorityQueue<K, P, PAGE, D>
where P: Clone,

Copies entries into a plain queue using one shard read lock at a time.

The snapshot is consistent within each shard and weakly consistent across shards. An entry that stays unchanged throughout the call is included if its insertion happens-before the call. Priority comparisons and clones must avoid calling back into this queue.

§Panics

Panics if the entries copied exceed the plain queue’s u32::MAX limit or if cloning or comparing priorities panics.

Trait Implementations§

Source§

impl<K: Key, P: Ord + Clone, const PAGE: usize, D: Directory> Clone for ConcurrentPriorityQueue<K, P, PAGE, D>

Rebuilds the queue from a weakly consistent snapshot with the same shard count. See ConcurrentPriorityQueue::snapshot for locking.

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K: Key + Debug, P: Debug, const PAGE: usize, D: Directory> Debug for ConcurrentPriorityQueue<K, P, PAGE, D>

Formats entries as a map using one shard read lock at a time, with the same consistency as ConcurrentPriorityQueue::snapshot. User formatting must avoid calling back into the queue.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<K: Key, P, const PAGE: usize, D: Directory> Default for ConcurrentPriorityQueue<K, P, PAGE, D>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, K: Key + Deserialize<'de>, P: Ord + Deserialize<'de>, const PAGE: usize, D: Directory> Deserialize<'de> for ConcurrentPriorityQueue<K, P, PAGE, D>

Reads the plain queue format and redistributes entries into the default number of shards.

Source§

fn deserialize<De: Deserializer<'de>>( deserializer: De, ) -> Result<Self, De::Error>

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<K: Key, P: Ord, const PAGE: usize, D: Directory> Extend<(K, P)> for ConcurrentPriorityQueue<K, P, PAGE, D>

Pushes entries under exclusive access. Later entries in a slot win.

Source§

fn extend<I: IntoIterator<Item = (K, P)>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<K: Key, P: Ord, const PAGE: usize, D: Directory> From<PagedPriorityQueue<K, P, PAGE, D>> for ConcurrentPriorityQueue<K, P, PAGE, D>

Moves a plain queue into the default number of shards by re-pushing its entries in O(n log n) time.

Source§

fn from(queue: PagedPriorityQueue<K, P, PAGE, D>) -> Self

Converts to this type from the input type.
Source§

impl<K: Key, P: Ord, const PAGE: usize, D: Directory> FromIterator<(K, P)> for ConcurrentPriorityQueue<K, P, PAGE, D>

Collects entries into the default number of shards. Later entries in a slot win.

Source§

fn from_iter<I: IntoIterator<Item = (K, P)>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl<K: Key, P, const PAGE: usize, D: Directory> IntoIterator for ConcurrentPriorityQueue<K, P, PAGE, D>

Consumes the queue and yields entries in arbitrary order.

Source§

type Item = (K, P)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<<ConcurrentPriorityQueue<K, P, PAGE, D> as IntoIterator>::Item>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<K: Key + Serialize, P: Serialize, const PAGE: usize, D: Directory> Serialize for ConcurrentPriorityQueue<K, P, PAGE, D>

Serializes a sequence of key-priority pairs in the plain queue format, holding one shard read lock at a time. User serialization must avoid calling back into the queue.

The length of the weakly consistent view is unknown upfront. For a serializer that requires a sequence length, serialize ConcurrentPriorityQueue::snapshot instead.

Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<K, P, const PAGE: usize, D> Forget for ConcurrentPriorityQueue<K, P, PAGE, D>

§

impl<K, P, const PAGE: usize, D> Freeze for ConcurrentPriorityQueue<K, P, PAGE, D>
where Box<[CachePadded<Shard<K, P, PAGE, D>>]>: Freeze,

§

impl<K, P, const PAGE: usize, D> Move for ConcurrentPriorityQueue<K, P, PAGE, D>

§

impl<K, P, const PAGE: usize, D> RefUnwindSafe for ConcurrentPriorityQueue<K, P, PAGE, D>
where Box<[CachePadded<Shard<K, P, PAGE, D>>]>: RefUnwindSafe,

§

impl<K, P, const PAGE: usize, D> Send for ConcurrentPriorityQueue<K, P, PAGE, D>
where Box<[CachePadded<Shard<K, P, PAGE, D>>]>: Send,

§

impl<K, P, const PAGE: usize, D> Sync for ConcurrentPriorityQueue<K, P, PAGE, D>
where Box<[CachePadded<Shard<K, P, PAGE, D>>]>: Sync,

§

impl<K, P, const PAGE: usize, D> Unpin for ConcurrentPriorityQueue<K, P, PAGE, D>
where Box<[CachePadded<Shard<K, P, PAGE, D>>]>: Unpin,

§

impl<K, P, const PAGE: usize, D> UnsafeUnpin for ConcurrentPriorityQueue<K, P, PAGE, D>
where Box<[CachePadded<Shard<K, P, PAGE, D>>]>: UnsafeUnpin,

§

impl<K, P, const PAGE: usize, D> UnwindSafe for ConcurrentPriorityQueue<K, P, PAGE, D>
where Box<[CachePadded<Shard<K, P, PAGE, D>>]>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.