Skip to main content

tcontract_exec/
faer.rs

1//! The parallelism faer gets from a placement token (feature `faer`).
2
3/// Runs `f` with the parallelism faer should use for `token`.
4///
5/// A token that carries a team (minted by a `threadteam::Team`, or a child of
6/// one) and has more than one slot hands faer its own team as `Par::Team`:
7/// faer's regions run on the reserved members as team sections, at the
8/// dispatch cost the floors were derived from. Any other token runs faer with
9/// `Par::Seq` on the calling thread and never enters a pool: only a team gives
10/// faer internal parallelism. Batch lanes still fork through `threadteam`
11/// before this point, so batch-level parallelism stays.
12///
13/// # Examples
14///
15/// ```
16/// use std::num::NonZeroUsize;
17/// let pool = threadteam::Pool::builder()
18///     .threads(2)
19///     .acquire_timeout(std::time::Duration::from_secs(10))
20///     .build()
21///     .unwrap();
22/// // A token without a team runs faer sequentially.
23/// let token = threadteam::Exec::new(&pool, 2).unwrap();
24/// assert!(tcontract_exec::with_faer_par(token, |par| matches!(par, faer::Par::Seq)));
25/// // A team token of two slots hands faer the team.
26/// let team = pool.into_team(2).unwrap();
27/// let token = team.exec(2);
28/// assert!(tcontract_exec::with_faer_par(token, |par| matches!(par, faer::Par::Team(_))));
29/// // One slot is sequential even on a team.
30/// let one = team.exec(2).limit(NonZeroUsize::MIN);
31/// assert!(tcontract_exec::with_faer_par(one, |par| matches!(par, faer::Par::Seq)));
32/// ```
33pub fn with_faer_par<R: Send>(
34    mut token: threadteam::Exec<'_>,
35    f: impl FnOnce(faer::Par<'_>) -> R + Send,
36) -> R {
37    if token.budget().get() > 1 && token.carries_team() {
38        // A carried team is handed over without acquisition, so `team` never
39        // refuses it.
40        return token
41            .team(|team| f(faer::Par::Team(team)))
42            .expect("a carried team is never refused");
43    }
44    f(faer::Par::Seq)
45}