tokio_util::task

Struct LocalPoolHandle

Source
pub struct LocalPoolHandle { /* private fields */ }
Available on crate feature rt only.
Expand description

A cloneable handle to a local pool, used for spawning !Send tasks.

Internally the local pool uses a tokio::task::LocalSet for each worker thread in the pool. Consequently you can also use tokio::task::spawn_local (which will execute on the same thread) inside the Future you supply to the various spawn methods of LocalPoolHandle.

§Examples

use std::rc::Rc;
use tokio::task;
use tokio_util::task::LocalPoolHandle;

#[tokio::main(flavor = "current_thread")]
async fn main() {
    let pool = LocalPoolHandle::new(5);

    let output = pool.spawn_pinned(|| {
        // `data` is !Send + !Sync
        let data = Rc::new("local data");
        let data_clone = data.clone();

        async move {
            task::spawn_local(async move {
                println!("{}", data_clone);
            });
     
            data.to_string()
        }   
    }).await.unwrap();
    println!("output: {}", output);
}

Implementations§

Source§

impl LocalPoolHandle

Source

pub fn new(pool_size: usize) -> LocalPoolHandle

Create a new pool of threads to handle !Send tasks. Spawn tasks onto this pool via LocalPoolHandle::spawn_pinned.

§Panics

Panics if the pool size is less than one.

Source

pub fn num_threads(&self) -> usize

Returns the number of threads of the Pool.

Source

pub fn get_task_loads_for_each_worker(&self) -> Vec<usize>

Returns the number of tasks scheduled on each worker. The indices of the worker threads correspond to the indices of the returned Vec.

Source

pub fn spawn_pinned<F, Fut>(&self, create_task: F) -> JoinHandle<Fut::Output>
where F: FnOnce() -> Fut + Send + 'static, Fut: Future + 'static, Fut::Output: Send + 'static,

Spawn a task onto a worker thread and pin it there so it can’t be moved off of the thread. Note that the future is not Send, but the FnOnce which creates it is.

§Examples
use std::rc::Rc;
use tokio_util::task::LocalPoolHandle;

#[tokio::main]
async fn main() {
    // Create the local pool
    let pool = LocalPoolHandle::new(1);

    // Spawn a !Send future onto the pool and await it
    let output = pool
        .spawn_pinned(|| {
            // Rc is !Send + !Sync
            let local_data = Rc::new("test");

            // This future holds an Rc, so it is !Send
            async move { local_data.to_string() }
        })
        .await
        .unwrap();

    assert_eq!(output, "test");
}
Source

pub fn spawn_pinned_by_idx<F, Fut>( &self, create_task: F, idx: usize, ) -> JoinHandle<Fut::Output>
where F: FnOnce() -> Fut + Send + 'static, Fut: Future + 'static, Fut::Output: Send + 'static,

Differs from spawn_pinned only in that you can choose a specific worker thread of the pool, whereas spawn_pinned chooses the worker with the smallest number of tasks scheduled.

A worker thread is chosen by index. Indices are 0 based and the largest index is given by num_threads() - 1

§Panics

This method panics if the index is out of bounds.

§Examples

This method can be used to spawn a task on all worker threads of the pool:

use tokio_util::task::LocalPoolHandle;

#[tokio::main]
async fn main() {
    const NUM_WORKERS: usize = 3;
    let pool = LocalPoolHandle::new(NUM_WORKERS);
    let handles = (0..pool.num_threads())
        .map(|worker_idx| {
            pool.spawn_pinned_by_idx(
                || {
                    async {
                        "test"
                    }
                },
                worker_idx,
            )
        })
        .collect::<Vec<_>>();

    for handle in handles {
        handle.await.unwrap();
    }
}

Trait Implementations§

Source§

impl Clone for LocalPoolHandle

Source§

fn clone(&self) -> LocalPoolHandle

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for LocalPoolHandle

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
Source§

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

Source§

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

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more