Skip to main content

BackgroundExecutor

Struct BackgroundExecutor 

Source
pub struct BackgroundExecutor { /* private fields */ }
Expand description

Runs Send futures on GPUI’s background executor.

Get one from App::background_executor or crate::AsyncApp::background_executor. Its futures must be Send and 'static, so they cannot borrow entities or contexts. Pass in plain data and return plain data. Native backends use worker threads; a single-threaded web build runs these futures on the browser’s main thread. See executors.

Implementations§

Source§

impl BackgroundExecutor

Source

pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self

Creates an executor that sends its work through dispatcher.

Platform code creates the executor. Apps get one from App::background_executor.

Source

pub fn scheduler_executor(&self) -> BackgroundExecutor

Returns the underlying scheduler executor, for code that takes one directly.

Source

pub fn spawn_dedicated<F, Fut>(&self, f: F) -> Task<Fut::Output> ⓘ
where F: FnOnce(SchedulerLocalExecutor) -> Fut + Send + 'static, Fut: Future + 'static, Fut::Output: Send + Sync + 'static,

Runs the future that f returns on a thread of its own, and returns a task for its result.

Use this instead of BackgroundExecutor::spawn for work whose polls need more stack than the shared background threads provide. A dedicated thread gets the standard library’s default stack of 2 MiB. Dropping the task cancels the work, as it does for any task.

Source

pub fn prevent_app_nap(&self, reason: &str) -> ActivityGuard

Prevents App Nap-style throttling while the returned guard is held.

This does not prevent the system from entering idle sleep.

Source

pub fn spawn<R>( &self, future: impl Future<Output = R> + Send + 'static, ) -> Task<R> ⓘ
where R: Send + 'static,

Schedules future on this executor and returns a task for its result.

On native targets, use this for computation or blocking I/O that should leave the main thread free. On a single-threaded web build it uses the main thread, so each poll must remain short. The future must be Send and 'static. To get the result on the main thread, await the task from a foreground future. Dropping the task cancels the future.

§Examples
use gpui::TestApp;

let app = TestApp::new();
let task = app.background_executor().spawn(async { 6 * 7 });
assert_eq!(app.foreground_executor().block_test(task), 42);
Source

pub fn spawn_with_priority<R>( &self, priority: Priority, future: impl Future<Output = R> + Send + 'static, ) -> Task<R> ⓘ
where R: Send + 'static,

Like BackgroundExecutor::spawn, but with a Priority.

Higher priorities are more likely to run first, but the order isn’t guaranteed. Priority::RealtimeAudio runs the future on a dedicated thread with realtime scheduling. Use it only for audio work.

Source

pub async fn scoped<'scope, F>(&self, scheduler: F)
where F: FnOnce(&mut Scope<'scope>),

Runs futures that may borrow from the caller in parallel, and waits for all of them to finish.

scheduler receives a Scope and spawns the futures on it. Unlike BackgroundExecutor::spawn, those futures needn’t be 'static, because the returned future doesn’t complete until they have. Dropping the returned future cancels the futures, and blocks until they are destroyed. If scheduler panics, the futures that haven’t started are dropped, and the panic unwinds without hanging.

§Examples
use std::sync::atomic::{AtomicUsize, Ordering};
use gpui::TestApp;

let app = TestApp::new();
let total = AtomicUsize::new(0);
app.foreground_executor().block_test(app.background_executor().scoped(|scope| {
    for n in 1..=3 {
        let total = &total;
        scope.spawn(async move {
            total.fetch_add(n, Ordering::SeqCst);
        });
    }
}));
assert_eq!(total.into_inner(), 6);
Source

pub async fn scoped_priority<'scope, F>(&self, priority: Priority, scheduler: F)
where F: FnOnce(&mut Scope<'scope>),

Like BackgroundExecutor::scoped, but runs every future in the scope at priority.

Source

pub fn now(&self) -> Instant

Returns the current time.

Use this in place of std::time::Instant::now so that tests can control time. In tests it reads the simulated clock, which moves only when the test advances it.

Source

pub fn timer(&self, duration: Duration) -> Task<()> ⓘ

Returns a task that completes after duration.

Await it to delay work or to repeat it on an interval. In tests, time moves only when the test calls BackgroundExecutor::advance_clock. Other work can delay the wake-up, so the real wait can be longer than duration. A zero duration returns a task that is already complete.

§Examples
use std::time::Duration;
use gpui::TestApp;

let app = TestApp::new();
let timer = app.background_executor().timer(Duration::from_millis(500));
app.advance_clock(Duration::from_millis(500));
assert!(timer.is_ready());
Source

pub fn simulate_random_delay(&self) -> impl Future<Output = ()> + use<>

Yields a random number of times, allowing other ready tasks to run between steps.

Await it between steps of a test to shake out ordering bugs. Only available in tests.

§Panics

Panics if this executor isn’t a test executor.

Source

pub fn advance_clock(&self, duration: Duration)

Moves the simulated clock forward by duration.

Ready tasks run as the clock passes each timer, in time order, so a task that waits on a timer resumes at the right moment. When the call returns, the clock reads its earlier value plus duration. Only available in tests.

§Panics

Panics if this executor isn’t a test executor.

Source

pub fn tick(&self) -> bool

Runs one unit of ready work in tests.

Returns true if it ran a task or fired a timer, and false if there was nothing to do. Only available in tests.

§Panics

Panics if this executor isn’t a test executor.

Source

pub fn run_until_parked(&self)

Runs ready tasks in tests until none can make progress.

This doesn’t move the simulated clock. A timer that hasn’t expired stays pending, until BackgroundExecutor::advance_clock moves time past it. Only available in tests.

Source

pub fn allow_parking(&self)

Lets blocking waits in tests sleep in real time when no test work can make progress.

By default, a blocking call that cannot progress panics. With parking allowed, it waits in real time instead, and the test fails if the wait lasts 15 seconds. Use this for tests that wait on real I/O. Undo it with BackgroundExecutor::forbid_parking.

Source

pub fn set_block_on_ticks(&self, range: RangeInclusive<usize>)

Sets the range that the tick budget of a ForegroundExecutor::block_with_timeout call is drawn from, in tests.

The default is 1 to 1000 ticks. Only available in tests.

Source

pub fn forbid_parking(&self)

Undoes BackgroundExecutor::allow_parking, so a blocking call that can’t progress panics again. Only available in tests.

Source

pub fn rng(&self) -> SharedRng

Returns the seeded random number generator that the test scheduler uses.

Draw from it when a test makes its own random choices, so that the choices repeat with the same SEED. Only available in tests.

Source

pub fn num_cpus(&self) -> usize

Returns the number of CPUs the dispatcher reports.

In tests this is 4 unless it was changed with BackgroundExecutor::set_num_cpus.

Source

pub fn set_num_cpus(&self, count: usize)

Sets the value that BackgroundExecutor::num_cpus returns, in tests.

§Panics

Panics if this executor isn’t a test executor.

Source

pub fn is_main_thread(&self) -> bool

Returns whether the current thread is the main thread.

Source

pub fn is_test(&self) -> bool

Whether this executor runs on the deterministic test scheduler.

Available in every build. Use it, rather than cfg(feature = "test-support"), for behavior that must differ under tests, so that compiling test-support into an application doesn’t change it.

Trait Implementations§

Source§

impl Clone for BackgroundExecutor

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

👎Deprecated since 0.7.7:

replaced by palette::chromatic_adaptation::AdaptIntoUnclamped

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

👎Deprecated since 0.7.7:

replaced by palette::chromatic_adaptation::AdaptIntoUnclamped

Convert the source color to the destination color using the bradford method by default.
Source§

impl<T, C> AdaptIntoUnclamped<T> for C
where T: AdaptFromUnclamped<C>,

Source§

type Scalar = <T as AdaptFromUnclamped<C>>::Scalar

The number type that’s used as the color’s components.
Source§

fn adapt_into_unclamped_with<M>(self) -> T

Adapt a color of type Self into a color of type T, using the custom matrix M. Read more
Source§

fn adapt_into_unclamped(self) -> T
where Bradford: LmsToXyz<Self::Scalar> + XyzToLms<Self::Scalar>,

Adapt a color of type Self into a color of type T, using the Bradford matrix. Read more
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, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
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<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

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

Source§

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

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

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<T, C> ComponentsInto<C> for T

Source§

fn components_into(self) -> C

Cast this collection of color components into a collection of colors. Read more
Source§

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

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
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, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

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

Initializes a with the given initializer. Read more
Source§

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

Dereferences the given pointer. Read more
Source§

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

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

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

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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