Skip to main content

block_on

Function block_on 

Source
pub fn block_on<F: Future>(future: F) -> F::Output
Expand description

Drive future to completion on the current thread, parking between polls.

A block_on may run inside a poll of another on the same thread (a future whose poll calls a helper built on this function). The two share the thread’s waker, and the inner one may take a wake that was the outer one’s: so when the inner one has taken a wake (whether it slept for it or found it noted already), the outer future is polled once more before it sleeps, whether or not the wake was its own. A future whose every poll runs a block_on that takes a wake is therefore polled again after each, with no wake of its own.

§Panics

On a thread that is ending, once its thread-local values are being destroyed: block_on keeps its waker and its state in thread-local storage, and a call from the destructor of another thread-local value may find them gone (the standard library’s panic for that).

§Examples

Two messages open at once, fed in turns, with Pipeline called again while handling a completed event:

use blake3_servil::{Mode, convenience, throughput::{Event, Limits, Pipeline, block_on}};

let mut pipeline = Pipeline::new(Mode::Plain, Limits { messages: 4, rooms: 4 });
block_on(async {
    let mut a = pipeline.message("A", None).await;
    let mut b = pipeline.message("B", None).await;
    let mut room = pipeline.room().await;
    room.bytes_mut()[..3].copy_from_slice(b"foo");
    pipeline.commit(&mut a, &mut room, 3);
    room.bytes_mut()[..4].copy_from_slice(b"quux");
    pipeline.commit(&mut b, &mut room, 4);
    drop(room);
    pipeline.end(a);
    pipeline.end(b);
    pipeline.ready().await;
    let mut seen = Vec::new();
    while seen.len() < 2 {
        if let Some(Event::Hashed { tag, hash, .. }) = pipeline.next_event() {
            seen.push((tag, hash));
            if tag == "A" {
                let follow = pipeline.message("C", None).await;
                pipeline.end(follow);
            }
        } else {
            pipeline.ready().await;
        }
    }
    assert_eq!(seen[0], ("A", convenience::hash(b"foo")));
    assert_eq!(seen[1], ("B", convenience::hash(b"quux")));
    while pipeline.next_event().is_none() {
        pipeline.ready().await;
    }
});

A task holding a Pipeline, Message, and Room across .await is Send and 'static (what tokio::spawn requires):

use blake3_servil::{Mode, throughput::{Limits, Pipeline, block_on}};
fn assert_send_static<F: core::future::Future + Send + 'static>(f: F) -> F { f }
async fn read(into: &mut [u8]) -> usize { into[..5].copy_from_slice(b"hello"); 5 }

let task = assert_send_static(async {
    let mut pipeline = Pipeline::<u64, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 2, rooms: 4 });
    let mut m = pipeline.message(7, None).await;
    let mut room = pipeline.room().await;
    let n = read(room.bytes_mut()).await;
    pipeline.commit(&mut m, &mut room, n);
    drop(room);
    pipeline.end(m);
    let whole = pipeline.message(8, None).await;
    pipeline.owned(whole, vec![1, 2, 3]);
    let mut got = 0;
    while got < 2 {
        if pipeline.next_event().is_some() { got += 1; } else { pipeline.ready().await; }
    }
});
block_on(task);

A message used after end is refused by the compiler:

ⓘ
use blake3_servil::throughput::{Pipeline, Room};
async fn bad(pipeline: &mut Pipeline<u64>, room: &mut Room) {
    let mut m = pipeline.message(1, None).await;
    pipeline.end(m);
    pipeline.commit(&mut m, room, 1);
}

A lent buffer cannot be freed while its Lent guard lives:

ⓘ
use blake3_servil::throughput::Pipeline;
async fn bad(pipeline: &mut Pipeline<u64>) {
    let buffer = vec![0u8; 1024];
    let m = pipeline.message(1, None).await;
    let guard = unsafe { pipeline.lent(m, &buffer) };
    drop(buffer);
    pipeline.ready().await;
    drop(guard);
}

nor mutated while its Lent guard lives:

ⓘ
use blake3_servil::throughput::Pipeline;
async fn bad(pipeline: &mut Pipeline<u64>) {
    let mut buffer = vec![0u8; 1024];
    let m = pipeline.message(1, None).await;
    let guard = unsafe { pipeline.lent(m, &buffer) };
    buffer[0] = 1;
    pipeline.ready().await;
    drop(guard);
}

Held until the event exists, lent compiles and drops cleanly before the buffer:

use blake3_servil::{Mode, convenience, throughput::{Event, Limits, Pipeline, block_on}};
let mut pipeline = Pipeline::new(Mode::Plain, Limits { messages: 2, rooms: 0 });
block_on(async {
    let buffer = vec![9u8; 1 << 20];
    let m = pipeline.message(1u64, None).await;
    let _guard = unsafe { pipeline.lent(m, &buffer) };
    pipeline.ready().await;
});
match pipeline.next_event() {
    Some(Event::Hashed { hash, .. }) => assert_eq!(hash, convenience::hash(&vec![9u8; 1 << 20])),
    _ => panic!("expected Hashed"),
}

Pipeline::new (without owner type) exposes no owned method:

ⓘ
use blake3_servil::throughput::Pipeline;
async fn bad(pipeline: &mut Pipeline<u64>) {
    let m = pipeline.message(1, None).await;
    pipeline.owned(m, ());
}

A batch over borrowed blocks is refused (Batch<'static> required):

ⓘ
use blake3_servil::throughput::{Batch, Block, Pipeline};
async fn bad(pipeline: &mut Pipeline<u64>, blocks: &[Block]) {
    let batch = Batch::from_blocks(blocks, 64);
    let m = pipeline.message(1, None).await;
    pipeline.batch(m, batch, Box::new([]));
}

Two concurrent waits on one pipeline are refused (&mut Pipeline):

ⓘ
use blake3_servil::throughput::Pipeline;
async fn bad(pipeline: &mut Pipeline<u64>) {
    let slot = pipeline.message(1, None);
    let ev = pipeline.ready();
    let _ = (slot.await, ev.await);
}