Skip to main content

ThreadScope

Trait ThreadScope 

Source
pub trait ThreadScope {
    // Required method
    fn scope<'env, Body: ScopeBody<'env>>(&self, body: Body) -> Body::Output;
}
Expand description

Bridges CompressMultiScoped to a scoped-thread API such as std::thread::scope or rayon::scope, so that neither has to be a dependency of this crate.

StdThreadScope implements this over std::thread::scope. A rayon-backed implementation is a handful of lines in the calling crate, and either of rayon’s two scope entry points will do — ScopeBody’s Send bounds are there so that rayon::scope, which requires both its body and its return value to be Send, is usable as well:

use simd_brotli::enc::threading::{ScopeBody, ScopedSpawner, ThreadScope};

struct RayonSpawner<'a, 'scope>(&'a rayon::Scope<'scope>);

impl<'a, 'scope, 'env: 'scope> ScopedSpawner<'env> for RayonSpawner<'a, 'scope> {
    fn spawn<Task: FnOnce() + Send + 'env>(&self, task: Task) {
        self.0.spawn(move |_| task());
    }
}

/// Runs the body on the calling thread; chunks go to the pool.
pub struct RayonThreadScope;

impl ThreadScope for RayonThreadScope {
    fn scope<'env, Body: ScopeBody<'env>>(&self, body: Body) -> Body::Output {
        rayon::in_place_scope(|scope| body.run(&RayonSpawner(scope)))
    }
}

/// Runs the body on the pool as well.
pub struct RayonPoolScope;

impl ThreadScope for RayonPoolScope {
    fn scope<'env, Body: ScopeBody<'env>>(&self, body: Body) -> Body::Output {
        rayon::scope(|scope| body.run(&RayonSpawner(scope)))
    }
}

Both produce identical output. Prefer in_place_scope when the calling thread is yours to use: the body compresses the last chunk itself, so running it in place keeps that work on this thread rather than handing it to a pool worker while this thread blocks on it. Reach for scope when the caller should not be doing encode work at all — inside an existing rayon task, say, or when the calling thread has to stay responsive.

Required Methods§

Source

fn scope<'env, Body: ScopeBody<'env>>(&self, body: Body) -> Body::Output

Opens a scope, runs body in it, and returns body’s output only once every task body spawned has finished.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl ThreadScope for StdThreadScope

Available on crate feature std only.