pub struct Barrier { /* 私有字段 */ }展开描述
barrier 使多个任务能够同步某些计算的开始。
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);实现§
源代码§impl Barrier
impl Barrier
源代码pub fn new(n: usize) -> Barrier
pub fn new(n: usize) -> Barrier
创建一个新的 barrier,可以阻塞给定数量的任务。
barrier 将阻塞调用 Barrier::wait 的 n-1 个任务,然后在第 n 个任务调用 wait 时立即唤醒所有任务。
源代码pub async fn wait(&self) -> BarrierWaitResult
pub async fn wait(&self) -> BarrierWaitResult
在所有任务都在此会合并之前不会解析。
barrier 在所有任务都已合并一次后可重用,并且可以连续使用。
单个(任意的)future 将收到一个 BarrierWaitResult,从此函数返回时该结果从 BarrierWaitResult::is_leader 返回 true,而所有其他任务将收到从 is_leader 返回 false 的结果。
§取消安全性
此方法不是取消安全的。
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 实现§
源代码§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
源代码§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. 更多信息