Struct LocalSet
struct LocalSet { ... }
A set of tasks which are executed on the same thread.
In some cases, it is necessary to run one or more futures that do not
implement Send and thus are unsafe to send between threads. In these
cases, a local task set may be used to schedule one or more !Send
futures to run together on the same thread.
For example, the following code will not compile:
use Rc;
async
Use with run_until
To spawn !Send futures, we can use a local task set to schedule them
on the thread calling Runtime::block_on. When running inside of the
local task set, we can use task::spawn_local, which can spawn
!Send futures. For example:
use Rc;
use task;
async
Note: The run_until method can only be used in #[tokio::main],
#[tokio::test] or directly inside a call to Runtime::block_on. It
cannot be used inside a task spawned with tokio::spawn.
Awaiting a LocalSet
Additionally, a LocalSet itself implements Future, completing when
all tasks spawned on the LocalSet complete. This can be used to run
several futures on a LocalSet and drive the whole set until they
complete. For example,
use ;
use Rc;
async
Note: Awaiting a LocalSet can only be done inside
#[tokio::main], #[tokio::test] or directly inside a call to
Runtime::block_on. It cannot be used inside a task spawned with
tokio::spawn.
Use inside tokio::spawn
The two methods mentioned above cannot be used inside tokio::spawn, so
to spawn !Send futures from inside tokio::spawn, we need to do
something else. The solution is to create the LocalSet somewhere else,
and communicate with it using an mpsc channel.
The following example puts the LocalSet inside a new thread.
use Builder;
use ;
use LocalSet;
// This struct describes the task you want to spawn. Here we include
// some simple examples. The oneshot channel allows sending a response
// to the spawner.
// This task may do !Send stuff. We use printing a number as an example,
// but it could be anything.
//
// The Task struct is an enum to support spawning many different kinds
// of operations.
async
async
Implementations
impl LocalSet
fn new() -> LocalSetReturns a new local task set.
fn enter(self: &Self) -> LocalEnterGuardEnters the context of this
LocalSet.The
spawn_localmethod will spawn tasks on theLocalSetwhose context you are inside.fn spawn_local<F>(self: &Self, future: F) -> JoinHandle<<F as >::Output> where F: Future + 'static, <F as >::Output: 'staticSpawns a
!Sendtask onto the local task set.This task is guaranteed to be run on the current thread.
Unlike the free function
spawn_local, this method may be used to spawn local tasks when theLocalSetis not running. The provided future will start running once theLocalSetis next started, even if you don't await the returnedJoinHandle.Examples
use task; asyncfn block_on<F>(self: &Self, rt: &Runtime, future: F) -> <F as >::Output where F: FutureRuns a future to completion on the provided runtime, driving any local futures spawned on this task set on the current thread.
This runs the given future on the runtime, blocking until it is complete, and yielding its resolved result. Any tasks or timers which the future spawns internally will be executed on the runtime. The future may also call
spawn_localtospawn_localadditional local futures on the current thread.This method should not be called from an asynchronous context.
Panics
This function panics if the executor is at capacity, if the provided future panics, or if called within an asynchronous execution context.
Notes
Since this function internally calls
Runtime::block_on, and drives futures in the local task set inside that call toblock_on, the local futures may not use in-place blocking. If a blocking call needs to be issued from a local task, thespawn_blockingAPI may be used instead.For example, this will panic:
use tokio::runtime::Runtime; use tokio::task; let rt = Runtime::new().unwrap(); let local = task::LocalSet::new(); local.block_on(&rt, async { let join = task::spawn_local(async { let blocking_result = task::block_in_place(|| { // ... }); // ... }); join.await.unwrap(); })This, however, will not panic:
use Runtime; use task; let rt = new.unwrap; let local = new; local.block_onasync fn run_until<F>(self: &Self, future: F) -> <F as >::Output where F: FutureRuns a future to completion on the local set, returning its output.
This returns a future that runs the given future with a local set, allowing it to call
spawn_localto spawn additional!Sendfutures. Any local futures spawned on the local set will be driven in the background until the future passed torun_untilcompletes. When the future passed torun_untilfinishes, any local futures which have not completed will remain on the local set, and will be driven on subsequent calls torun_untilor when awaiting the local set itself.Cancel safety
This method is cancel safe when
futureis cancel safe.Examples
use task; async
impl Debug for LocalSet
fn fmt(self: &Self, fmt: &mut Formatter<'_>) -> Result
impl Default for LocalSet
fn default() -> LocalSet
impl Drop for LocalSet
fn drop(self: &mut Self)
impl Freeze for LocalSet
impl Future for LocalSet
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<<Self as >::Output>
impl RefUnwindSafe for LocalSet
impl Send for LocalSet
impl Sync for LocalSet
impl Unpin for LocalSet
impl UnsafeUnpin for LocalSet
impl UnwindSafe for LocalSet
impl<F> IntoFuture for LocalSet
fn into_future(self: Self) -> <F as IntoFuture>::IntoFuture
impl<T> Any for LocalSet
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for LocalSet
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for LocalSet
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> From for LocalSet
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into for LocalSet
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for LocalSet
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for LocalSet
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>