Skip to content

Commit

Permalink
feat(maitake): add wait::Semaphore (#301)
Browse files Browse the repository at this point in the history
A semaphore is a useful synchronization type for things like
rate-limiting async tasks. It could also be used as a lower-level
primitive to implement things like read-write locks[^1] and
channels[^2].

This branch adds an asynchronous semaphore implementation in
`maitake::wait`. The implementation is based on the implementation I
wrote for Tokio in tokio-rs/tokio#2325, with some code simplified a bit
as it was not necessary to maintain Tokio's required API surface.

Closes #299 

[^1]: a rwlock can be modeled by a semaphore with _n_ permits (where _n_
    is the maximum number of concurrent readers); each reader must
    acquire a single permit, while a writer must acquire _n_ permits).

[^2]: a bounded MPSC channel of capacity _n_ can be implemented using a
    semaphore with _n_ permits, where each producer must acquire a
    single permit to write, and every time a message is consumed, the
    reader releases a permit to the writers.
  • Loading branch information
hawkw authored Aug 30, 2022
1 parent 366d4d5 commit 8a46328
Show file tree
Hide file tree
Showing 4 changed files with 1,339 additions and 1 deletion.
7 changes: 6 additions & 1 deletion maitake/src/wait.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
//! Waiter cells and queues to allow tasks to wait for notifications.
//!
//! This module implements three types of structure for waiting:
//! This module implements the following primitives for waiting:
//!
//! - [`WaitCell`], which stores a *single* waiting task
//! - [`WaitQueue`], a queue of waiting tasks, which are woken in first-in,
//! first-out order
//! - [`WaitMap`], a set of waiting tasks associated with keys, in which a task
//! can be woken by its key
//! - [`Semaphore`]: an asynchronous [counting semaphore], for limiting the
//! number of tasks which may run concurrently
pub(crate) mod cell;
pub mod map;
pub mod queue;
pub mod semaphore;

pub use self::cell::WaitCell;
#[doc(inline)]
pub use self::map::WaitMap;
#[doc(inline)]
pub use self::queue::WaitQueue;
#[doc(inline)]
pub use self::semaphore::Semaphore;

use core::task::Poll;

Expand Down
Loading

0 comments on commit 8a46328

Please sign in to comment.