[][src]Crate async_weighted_semaphore

An async weighted semaphore: a synchronization primitive for limiting concurrent usage of a resource or signaling availability of a resource to a consumer.

A Semaphore starts with an initial counter of permits. Calling release will increase the counter. Calling acquire will attempt to decrease the counter, waiting if the counter would be negative.


A semaphore can limit memory usage of concurrent futures:

struct ChecksumPool(Semaphore);
impl ChecksumPool{
    async fn checksum(&self, path: &str) -> io::Result<u64> {
        let len = fs::metadata(path).await?.len();
        // Acquire enough permits to create a buffer
        let _guard = self.0.acquire(len as usize).await.unwrap();
        // Create a buffer
        let contents = fs::read(path).await?;
        Ok(contents.into_iter().map(|x| x as u64).sum::<u64>())
        // End of scope: buffer is dropped and then _guard is dropped, releasing the permits.

A semaphore can limit memory usage of a producer-consumer queue:

use async_channel::{Sender, Receiver, unbounded, SendError};
let (sender, receiver) = unbounded();
let sender = async move {
    // The total size of strings in queue and being parsed will not exceed 10.
    let capacity = 10;
    let semaphore = Arc::new(Semaphore::new(capacity));
    for i in 0..100 {
        let data = format!("{}", i);
        // Don't deadlock if data.len() exceeds capacity.
        let permits = data.len().max(capacity);
        let guard = semaphore.acquire_arc(permits).await.unwrap();
        if let Err(SendError(_)) = sender.send((guard, data)).await {
let receiver = async {
    for i in 0..100 {
        if let Ok((guard, data)) = receiver.recv().await{
            assert_eq!(Ok(i), data.parse());
            // Drop guard after data to ensure data being parsed counts against the capacity.
join!(receiver, sender);

A semaphore can signal the availability of data for batch processing:

let buffer1 = Arc::new((Semaphore::new(0), Mutex::new(VecDeque::<u8>::new())));
let buffer2 = buffer1.clone();
let sender = async move {
    for i in 0..100 {
    // Indicate no more data will arrive.
let receiver = async {
    for i in 0..100 {
        if let Ok(guard) = buffer2.0.acquire(2).await {
        let batch = buffer2.1.lock().await.drain(0..2).collect::<Vec<_>>();
        assert!(batch == b"" || batch == b"A" || batch == b"AA");
        if batch.len() < 2 {
join!(receiver, sender);


Acquiring has "first-in-first-out" semantics: calls to acquire finish in the same order that they start. If there is a pending call to acquire, a new call to acquire will always block, even if there are enough permits available for the new call. This policy reduces starvation and tail latency at the cost of utilization.

let sem = Semaphore::new(1);
let a = sem.acquire(2);
let b = sem.acquire(1);
assert!(poll!(&mut a).is_pending());
assert!(poll!(&mut b).is_pending());


If a guard is dropped while panicking, or the number of available permits exceeds Semaphore::MAX_AVAILABLE, the semaphore will be permanently poisoned. All current and future acquires will fail, and release will become a no-op. This is similar in principle to poisoning a std::sync::Mutex. Explicitly poisoning with Semaphore::poison can also be useful to coordinate termination (e.g. closing a producer-consumer channel).


Semaphore uses no heap allocations. Most calls are lock-free. The only operation that may wait for a lock is cancellation: if a AcquireFuture or AcquireFutureArc is dropped before Future::poll returns Poll::Ready, the drop may synchronously wait for a lock.



A Future returned by Semaphore::acquire that produces a SemaphoreGuard.


A Future returned by Semaphore::acquire_arc that produces a SemaphoreGuardArc.


An error returned by Semaphore::acquire and Semaphore::acquire_arc to indicate the Semaphore has been poisoned. See Semaphore::acquire_arc for an example usage.


An async weighted semaphore. See crate documentation for usage.


A guard returned by Semaphore::acquire that will call Semaphore::release when it is dropped (falls out of scope).


A guard returned by Semaphore::acquire_arc that will call Semaphore::release when it is dropped (falls out of scope). Can be sent between threads.



An error returned from Semaphore::try_acquire and Semaphore::try_acquire_arc. See Semaphore::try_acquire_arc for an example usage.