pub struct TokioTp { /* private fields */ }
Available on crate feature tokio_tp only.
Expand description

An executor that uses tokio::runtime::Runtime.

Example

The following example shows how to pass an executor to a library function.

use
{
   futures          :: { task::{ Spawn, SpawnExt } } ,
   async_executors  :: { TokioTp                   } ,
   tokio::runtime   :: { Builder                   } ,
   std::convert     :: { TryFrom                   } ,
   futures::channel :: { oneshot, oneshot::Sender  } ,
};


fn lib_function( exec: impl Spawn, tx: Sender<&'static str> )
{
   exec.spawn( async
   {
      tx.send( "I can spawn from a library" ).expect( "send string" );

   }).expect( "spawn task" );
}


fn main()
{
   // This creates the runtime with defaults. It enables io and timers based on
   // the features enabled on _async_executors_. You can also create `TokioTp` from
   // a tokio `Runtime` or a `Handle`.
   //
   let exec = TokioTp::new().expect( "create tokio threadpool" );

   let program = async
   {
      let (tx, rx) = oneshot::channel();

      lib_function( &exec, tx );
      assert_eq!( "I can spawn from a library", rx.await.expect( "receive on channel" ) );
   };

   exec.block_on( program );
}

Unwind Safety.

You must only spawn futures to this API that are unwind safe. Tokio will wrap it in std::panic::AssertUnwindSafe and wrap the poll invocation with std::panic::catch_unwind.

They reason that this is fine because they require Send + 'static on the future. As far as I can tell this is wrong. Unwind safety can be circumvented in several ways even with Send + 'static (eg. parking_lot::Mutex is Send + 'static but !UnwindSafe).

You should make sure that if your future panics, no code that lives on after the spawned task has unwound, nor any destructors called during the unwind can observe data in an inconsistent state.

If a future is run with block_on as opposed to spawn, the panic will not be caught and the thread calling block_on will be unwound.

Note that unwind safety is related to logic errors, not related to the memory safety issues that cannot happen in safe rust (memory safety, undefined behavior, unsoundness, data races, …). See the relevant catch_unwind RFC and it’s discussion threads for more info as well as the documentation of std::panic::UnwindSafe.

Implementations§

source§

impl TokioTp

source

pub fn new() -> Result<Self, TokioTpErr>

Create a new TokioTp. Uses a default multithreaded Runtime setting timers and io depending on the features enabled on async_executors.

source

pub fn try_current() -> Result<Self, TokioTpErr>

Try to construct a TokioTp from the currently entered Runtime. You can do this if you want to construct your runtime with the tokio macros eg:

#[tokio::main]
async fn main()
{
   // ...
}
Warning

TokioTp::new() is preferred over this. It’s brief, doesn’t require macros and is the intended behavior for this type. The whole library aims at a paradigm without global executors.

The main footgun here is that you are now already in async context, so you must not call TokioTp::block_on. block_on will panic when run from within an existing async context.

Errors

Will fail if trying to construct from a current thread runtime or if no runtime is running.

source

pub fn block_on<F: Future>(&self, f: F) -> F::Output

Forwards to Runtime::block_on or Handle::block_on.

Panics

If called when a runtime is already entered (eg. in async context), like when you created this executor with TokioTp::try_current, this will panic.

source

pub fn shutdown_timeout(self, duration: Duration) -> Result<(), TokioTpErr>

See: tokio::runtime::Runtime::shutdown_timeout

This tries to unwrap the Arc<Runtime> we hold, so that works only if no other clones are around. If this is not the only reference, self will be returned to you as an error. It means you cannot shutdown the runtime because there are other clones of the executor still alive.

Errors
source

pub fn shutdown_background(self) -> Result<(), TokioTpErr>

See: tokio::runtime::Runtime::shutdown_background

This tries to unwrap the Arc<Runtime> we hold, so that works only if no other clones are around. If this is not the only reference, self will be returned to you as an error. It means you cannot shutdown the runtime because there are other clones of the executor still alive.

Errors

Trait Implementations§

source§

impl Clone for TokioTp

source§

fn clone(&self) -> TokioTp

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 TokioTp

source§

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

Formats the value using the given formatter. Read more
source§

impl Spawn for TokioTp

source§

fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError>

Never fails.

source§

fn status(&self) -> Result<(), SpawnError>

Determines whether the executor is able to spawn new tasks. Read more
source§

impl<R: Send + 'static> SpawnBlocking<R> for TokioTp

source§

fn spawn_blocking<F>(&self, f: F) -> BlockingHandle<R> where F: FnOnce() -> R + Send + 'static,

Runs the provided closure on a thread where blocking is acceptable.
source§

fn spawn_blocking_dyn( &self, f: Box<dyn FnOnce() -> R + Send> ) -> BlockingHandle<R>

Runs the provided closure on a thread where blocking is acceptable. This part of the trait is object safe but your closure must be boxed and you cannot have a return value.
source§

impl<Out: 'static + Send> SpawnHandle<Out> for TokioTp

source§

fn spawn_handle_obj( &self, future: FutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError>

Spawn a future and return a JoinHandle that can be awaited for the output of the future.
source§

impl Timer for TokioTp

Available on crate feature tokio_timer only.
source§

fn sleep(&self, dur: Duration) -> BoxFuture<'static, ()>

Future that resolves after a given duration.
source§

impl TryFrom<Handle> for TokioTp

Allows to create a TokioTp from a Handle.

Errors

Will fail if you pass a multithreaded runtime. In that case it will return your Handle.

§

type Error = Handle

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

fn try_from(handle: Handle) -> Result<Self, Handle>

Performs the conversion.
source§

impl TryFrom<Runtime> for TokioTp

Allows to create a TokioTp from a Runtime.

Errors

Will fail if you pass a multithreaded runtime. In that case it will return your Runtime.

§

type Error = Runtime

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

fn try_from(rt: Runtime) -> Result<Self, Runtime>

Performs the conversion.
source§

impl YieldNow for TokioTp

source§

fn yield_now(&self) -> YieldNowFut

Await this future in order to yield to the executor.
source§

impl TokioIo for TokioTp

Available on crate feature tokio_io only.

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. 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> 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 Twhere 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.

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<Sp> SpawnExt for Spwhere Sp: Spawn + ?Sized,

source§

fn spawn<Fut>(&self, future: Fut) -> Result<(), SpawnError>where Fut: Future<Output = ()> + Send + 'static,

Spawns a task that polls the given future with output () to completion. Read more
source§

fn spawn_with_handle<Fut>( &self, future: Fut ) -> Result<RemoteHandle<<Fut as Future>::Output>, SpawnError>where Fut: Future + Send + 'static, <Fut as Future>::Output: Send,

Spawns a task that polls the given future to completion and returns a future that resolves to the spawned future’s output. Read more
source§

impl<T, Out> SpawnHandleExt<Out> for Twhere T: SpawnHandle<Out> + ?Sized, Out: 'static + Send,

source§

fn spawn_handle( &self, future: impl Future<Output = Out> + Send + 'static ) -> Result<JoinHandle<Out>, SpawnError>

Spawn a future and return a JoinHandle that can be awaited for the output of the future.
source§

impl<T> TimerExt for Twhere T: Timer,

source§

fn timeout<F: Future>(&self, duration: Duration, future: F) -> Timeout<F>

Wrap a Future with a timeout. Read more
source§

impl<T> ToOwned for Twhere T: Clone,

§

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 Twhere U: Into<T>,

§

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 Twhere U: TryFrom<T>,

§

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
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