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
impl Barrier
Sourcepub fn new(n: usize) -> Barrier
pub fn new(n: usize) -> Barrier
创建一个新的屏報,可以阻塞给定数量的任务。
屏報会阻塞 -1 个调用 n 的任务,然后在第 Barrier::wait 个任务调用 n 时一并唤醒所有任务。wait
Sourcepub async fn wait(&self) -> BarrierWaitResult
pub async fn wait(&self) -> BarrierWaitResult
在所有任务都在此处匹配完毕之前不会完成。
屏報在所有任务都圱到完包合点后可以重复使用,可连续循圍使用。
一个单包包(任愊)的 future 会收到一个 ,其 BarrierWaitResult 返回 is_leader,其他所有任务收到的 true 返回 is_leader。false
§Cancel safety
此方法不安全称叫没安全叫的。
Trait 实现§
自动 Trait 实现§
impl !Freeze for Barrier
impl !RefUnwindSafe for Barrier
impl Send for Barrier
impl Sync for Barrier
impl Unpin for Barrier
impl UnsafeUnpin for Barrier
impl !UnwindSafe for Barrier
Blanket 实现§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. 更多信息