Barrier in async_std::sync - Rust (original) (raw)

pub struct Barrier { /* private fields */ }

Available on unstable only.

Expand description

A counter to synchronize multiple tasks at the same time.

Source§

Source

Creates a barrier that can block the given number of tasks.

A barrier will block n-1 tasks which call wait() and then wake up all tasks at once when the nth task calls wait().

§Examples
use async_lock::Barrier;

let barrier = Barrier::new(5);

Source

Blocks the current task until all tasks reach this point.

Barriers are reusable after all tasks have synchronized, and can be used continuously.

Returns a BarrierWaitResult indicating whether this task is the “leader”, meaning the last task to call this method.

§Examples
use async_lock::Barrier;
use futures_lite::future;
use std::sync::Arc;
use std::thread;

let barrier = Arc::new(Barrier::new(5));

for _ in 0..5 {
    let b = barrier.clone();
    thread::spawn(move || {
        future::block_on(async {
            // The same messages will be printed together.
            // There will NOT be interleaving of "before" and "after".
            println!("before wait");
            b.wait().await;
            println!("after wait");
        });
    });
}

Source

Blocks the current thread until all tasks reach this point.

Barriers are reusable after all tasks have synchronized, and can be used continuously.

Returns a BarrierWaitResult indicating whether this task is the “leader”, meaning the last task to call this method.

§Blocking

Rather than using asynchronous waiting, like the wait method, this method will block the current thread until the wait is complete.

This method should not be used in an asynchronous context. It is intended to be used in a way that a barrier can be used in both asynchronous and synchronous contexts. Calling this method in an asynchronous context may result in a deadlock.

§Examples
use async_lock::Barrier;
use futures_lite::future;
use std::sync::Arc;
use std::thread;

let barrier = Arc::new(Barrier::new(5));

for _ in 0..5 {
    let b = barrier.clone();
    thread::spawn(move || {
        // The same messages will be printed together.
        // There will NOT be interleaving of "before" and "after".
        println!("before wait");
        b.wait_blocking();
        println!("after wait");
    });
}

§

§

§

§

§

§