跳到主要内容

Barrier

搜索

结构体 Barrier 

Source
pub struct Barrier { /* private fields */ }
展开描述

Barrier(屏障)使多个 task 能够同步开始某段计算。

use tokio::sync::Barrier;
use std::sync::Arc;

let mut handles = Vec::with_capacity(10);
let barrier = Arc::new(Barrier::new(10));
for _ in 0..10 {
    let c = barrier.clone();
    // The same messages will be printed together.
    // You will NOT see any interleaving.
    handles.push(tokio::spawn(async move {
        println!("before wait");
        let wait_result = c.wait().await;
        println!("after wait");
        wait_result
    }));
}

// Will not resolve until all "after wait" messages have been printed
let mut num_leaders = 0;
for handle in handles {
    let wait_result = handle.await.unwrap();
    if wait_result.is_leader() {
        num_leaders += 1;
    }
}

// Exactly one barrier will resolve as the "leader"
assert_eq!(num_leaders, 1);

实现§

Source§

impl Barrier

Source

pub fn new(n: usize) -> Barrier

创建一个新的屏報,可以阻塞给定数量的任务。

屏報会阻塞 n-1 个调用 Barrier::wait 的任务,然后在第 n 个任务调用 wait 时一并唤醒所有任务。

Source

pub async fn wait(&self) -> BarrierWaitResult

在所有任务都在此处匹配完毕之前不会完成。

屏報在所有任务都圱到完包合点后可以重复使用,可连续循圍使用。

一个单包包(任愊)的 future 会收到一个 BarrierWaitResult,其 is_leader 返回 true,其他所有任务收到的 is_leader 返回 false

§Cancel safety

此方法不安全称叫没安全叫的。

Trait 实现§

Source§

impl Debug for Barrier

Source§

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

使用给定的格式化器格式化此值。 更多信息

自动 Trait 实现§

Blanket 实现§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. 更多信息
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. 更多信息
Source§

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

Source§

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

Mutably borrows from an owned value. 更多信息
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

原样返回传入的参数。

Source§

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

Source§

fn into(self) -> U

调用 U::from(self)

也就是说,此转换的具体行为取决于 From<T> for U 的实现方式。

Source§

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

Source§

type Error = Infallible

转换出错时返回的类型。
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

执行转换。
Source§

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

Source§

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

转换出错时返回的类型。
Source§

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

执行转换。