Struct tokio_util::task::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 T)

🔬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