pax_global_header00006660000000000000000000000064146671077120014525gustar00rootroot0000000000000052 comment=62a83b15d76202d7908cd49350e22952b7b3b079 async-executor-1.13.1/000077500000000000000000000000001466710771200145615ustar00rootroot00000000000000async-executor-1.13.1/.github/000077500000000000000000000000001466710771200161215ustar00rootroot00000000000000async-executor-1.13.1/.github/dependabot.yml000066400000000000000000000002331466710771200207470ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: cargo directory: / schedule: interval: weekly commit-message: prefix: '' labels: [] async-executor-1.13.1/.github/workflows/000077500000000000000000000000001466710771200201565ustar00rootroot00000000000000async-executor-1.13.1/.github/workflows/ci.yml000066400000000000000000000055001466710771200212740ustar00rootroot00000000000000name: CI permissions: contents: read on: pull_request: push: branches: - master schedule: - cron: '0 2 * * 0' env: CARGO_INCREMENTAL: 0 CARGO_NET_GIT_FETCH_WITH_CLI: true CARGO_NET_RETRY: 10 CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 RUSTFLAGS: -D warnings RUSTDOCFLAGS: -D warnings RUSTUP_MAX_RETRIES: 10 defaults: run: shell: bash jobs: test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest] rust: [nightly, beta, stable] steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} - run: rustup target add wasm32-unknown-unknown - uses: taiki-e/install-action@cargo-hack - run: cargo build --all --all-features --all-targets if: startsWith(matrix.rust, 'nightly') - name: Run cargo check (without dev-dependencies to catch missing feature flags) if: startsWith(matrix.rust, 'nightly') run: cargo check -Z features=dev_dep - run: cargo test - run: cargo test --all-features - run: cargo check --all --all-features --target wasm32-unknown-unknown - run: cargo hack build --all --all-features --target wasm32-unknown-unknown --no-dev-deps msrv: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install cargo-hack uses: taiki-e/install-action@cargo-hack - run: cargo hack build --rust-version clippy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup update stable - run: cargo clippy --all-features --all-targets fmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup update stable - run: cargo fmt --all --check miri: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup toolchain install nightly --component miri && rustup default nightly - run: cargo miri test env: MIRIFLAGS: -Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-disable-isolation RUSTFLAGS: ${{ env.RUSTFLAGS }} -Z randomize-layout - run: cargo miri test --all-features env: MIRIFLAGS: -Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-disable-isolation -Zmiri-ignore-leaks RUSTFLAGS: ${{ env.RUSTFLAGS }} -Z randomize-layout security_audit: permissions: checks: write contents: read issues: write runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 # https://github.com/rustsec/audit-check/issues/2 - uses: rustsec/audit-check@master with: token: ${{ secrets.GITHUB_TOKEN }} async-executor-1.13.1/.github/workflows/release.yml000066400000000000000000000006411466710771200223220ustar00rootroot00000000000000name: Release permissions: contents: write on: push: tags: - v[0-9]+.* jobs: create-release: if: github.repository_owner == 'smol-rs' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/create-gh-release-action@v1 with: changelog: CHANGELOG.md branch: master env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} async-executor-1.13.1/.gitignore000066400000000000000000000000231466710771200165440ustar00rootroot00000000000000/target Cargo.lock async-executor-1.13.1/CHANGELOG.md000066400000000000000000000060201466710771200163700ustar00rootroot00000000000000# Version 1.13.1 - Fix docs.rs build. (#125) # Version 1.13.0 - Relax the `Send` bound on `LocalExecutor::spawn_many`. (#120) - Ensure all features are documented on `docs.rs`. (#122) # Version 1.12.0 - Add static executors, which are an optimization over executors that are kept around forever. (#112) # Version 1.11.0 - Re-export the `async_task::FallibleTask` primitive. (#113) - Support racy initialization of the executor state. This should allow the executor to be initialized on web targets without any issues. (#108) # Version 1.10.0 - Add a function `spawn_batch` that allows users to spawn multiple tasks while only locking the executor once. (#92) # Version 1.9.1 - Remove the thread-local optimization due to the bugs that it introduces. (#106) # Version 1.9.0 - Re-introduce the thread-local task push optimization to the executor. (#93) - Bump `async-task` to v4.4.0. (#90) - Replace some unnecessary atomic operations with non-atomic operations. (#94) - Use weaker atomic orderings for notifications. (#95) - When spawning a future, avoid looking up the ID to assign to that future twice. (#96) # Version 1.8.0 - When spawned tasks panic, the panic is caught and then surfaced in the spawned `Task`. Previously, the panic would be surfaced in `tick()` or `run()`. (#78) # Version 1.7.2 - Fix compilation under WebAssembly targets (#77). # Version 1.7.1 - Fix compilation under WebAssembly targets (#75). - Add a disclaimer indicating that this is a reference executor (#74). # Version 1.7.0 - Bump `async-lock` and `futures-lite` to their latest versions. (#70) # Version 1.6.0 - Remove the thread-local queue optimization, as it caused a number of bugs in production use cases. (#61) # Version 1.5.4 - Fix a panic that could happen when two concurrent `run()` calls are made and the thread local task slot is left as `None`. (#55) # Version 1.5.3 - Fix an accidental breaking change in v1.5.2, where `ex.run()` was no longer `Send`. (#50) - Remove the unused `memchr` dependency. (#51) # Version 1.5.2 - Add thread-local task queue optimizations, allowing new tasks to avoid using the global queue. (#37) - Update `fastrand` to v2. (#45) # Version 1.5.1 - Implement a better form of debug output for Executor and LocalExecutor. (#33) # Version 1.5.0 - Remove the dependency on the `once_cell` crate to restore the MSRV. (#29) - Update `concurrent-queue` to v2. # Version 1.4.1 - Remove dependency on deprecated `vec-arena`. (#23) # Version 1.4.0 - Add `Executor::is_empty()` and `LocalExecutor::is_empty()`. # Version 1.3.0 - Parametrize executors over a lifetime to allow spawning non-`static` futures. # Version 1.2.0 - Update `async-task` to v4. # Version 1.1.1 - Replace `AtomicU64` with `AtomicUsize`. # Version 1.1.0 - Use atomics to make `Executor::run()` and `Executor::tick()` futures `Send + Sync`. # Version 1.0.0 - Stabilize. # Version 0.2.1 - Add `try_tick()` and `tick()` methods. # Version 0.2.0 - Redesign the whole API. # Version 0.1.2 - Add the `Spawner` API. # Version 0.1.1 - Initial version async-executor-1.13.1/Cargo.toml000066400000000000000000000024101466710771200165060ustar00rootroot00000000000000[package] name = "async-executor" # When publishing a new version: # - Update CHANGELOG.md # - Create "v1.x.y" git tag version = "1.13.1" authors = ["Stjepan Glavina ", "John Nunley "] edition = "2021" rust-version = "1.63" description = "Async executor" license = "Apache-2.0 OR MIT" repository = "https://github.com/smol-rs/async-executor" keywords = ["asynchronous", "executor", "single", "multi", "spawn"] categories = ["asynchronous", "concurrency"] exclude = ["/.*"] [features] # Adds support for executors optimized for use in static variables. static = [] [dependencies] async-task = "4.4.0" concurrent-queue = "2.5.0" fastrand = "2.0.0" futures-lite = { version = "2.0.0", default-features = false } slab = "0.4.4" [target.'cfg(target_family = "wasm")'.dependencies] futures-lite = { version = "2.0.0", default-features = false, features = ["std"] } [dev-dependencies] async-channel = "2.0.0" async-io = "2.1.0" async-lock = "3.0.0" criterion = { version = "0.5", default-features = false, features = ["cargo_bench_support"] } easy-parallel = "3.1.0" fastrand = "2.0.0" futures-lite = "2.0.0" once_cell = "1.16.0" [[bench]] name = "executor" harness = false required-features = ["static"] [package.metadata.docs.rs] all-features = true async-executor-1.13.1/LICENSE-APACHE000066400000000000000000000251371466710771200165150ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. async-executor-1.13.1/LICENSE-MIT000066400000000000000000000017771466710771200162310ustar00rootroot00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. async-executor-1.13.1/README.md000066400000000000000000000031211466710771200160350ustar00rootroot00000000000000# async-executor [![Build](https://github.com/smol-rs/async-executor/workflows/Build%20and%20test/badge.svg)]( https://github.com/smol-rs/async-executor/actions) [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)]( https://github.com/smol-rs/async-executor) [![Cargo](https://img.shields.io/crates/v/async-executor.svg)]( https://crates.io/crates/async-executor) [![Documentation](https://docs.rs/async-executor/badge.svg)]( https://docs.rs/async-executor) Async executors. This crate provides two reference executors that trade performance for functionality. They should be considered reference executors that are "good enough" for most use cases. For more specialized use cases, consider writing your own executor on top of [`async-task`]. [`async-task`]: https://crates.io/crates/async-task ## Examples ```rust use async_executor::Executor; use futures_lite::future; // Create a new executor. let ex = Executor::new(); // Spawn a task. let task = ex.spawn(async { println!("Hello world"); }); // Run the executor until the task completes. future::block_on(ex.run(task)); ``` ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. #### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. async-executor-1.13.1/benches/000077500000000000000000000000001466710771200161705ustar00rootroot00000000000000async-executor-1.13.1/benches/executor.rs000066400000000000000000000534311466710771200204020ustar00rootroot00000000000000use std::mem; use std::thread::available_parallelism; use async_executor::{Executor, StaticExecutor}; use criterion::{criterion_group, criterion_main, Criterion}; use futures_lite::{future, prelude::*}; const TASKS: usize = 300; const STEPS: usize = 300; const LIGHT_TASKS: usize = 25_000; static EX: Executor<'_> = Executor::new(); static STATIC_EX: StaticExecutor = StaticExecutor::new(); fn run(f: impl FnOnce(), multithread: bool) { let limit = if multithread { available_parallelism().unwrap().get() } else { 1 }; let (s, r) = async_channel::bounded::<()>(1); easy_parallel::Parallel::new() .each(0..limit, |_| future::block_on(EX.run(r.recv()))) .finish(move || { let _s = s; f() }); } fn run_static(f: impl FnOnce(), multithread: bool) { let limit = if multithread { available_parallelism().unwrap().get() } else { 1 }; let (s, r) = async_channel::bounded::<()>(1); easy_parallel::Parallel::new() .each(0..limit, |_| future::block_on(STATIC_EX.run(r.recv()))) .finish(move || { let _s = s; f() }); } fn create(c: &mut Criterion) { c.bench_function("executor::create", |b| { b.iter(|| { let ex = Executor::new(); let task = ex.spawn(async {}); future::block_on(ex.run(task)); }) }); } fn running_benches(c: &mut Criterion) { for (prefix, with_static) in [("executor", false), ("static_executor", true)] { for (group_name, multithread) in [("single_thread", false), ("multi_thread", true)].iter() { let mut group = c.benchmark_group(group_name.to_string()); group.bench_function(format!("{}::spawn_one", prefix), |b| { if with_static { run_static( || { b.iter(|| { future::block_on(async { STATIC_EX.spawn(async {}).await }); }); }, *multithread, ); } else { run( || { b.iter(|| { future::block_on(async { EX.spawn(async {}).await }); }); }, *multithread, ); } }); if !with_static { group.bench_function("executor::spawn_batch", |b| { run( || { let mut handles = vec![]; b.iter(|| { EX.spawn_many((0..250).map(|_| future::yield_now()), &mut handles); }); handles.clear(); }, *multithread, ) }); } group.bench_function(format!("{}::spawn_many_local", prefix), |b| { if with_static { run_static( || { b.iter(move || { future::block_on(async { let mut tasks = Vec::new(); for _ in 0..LIGHT_TASKS { tasks.push(STATIC_EX.spawn(async {})); } for task in tasks { task.await; } }); }); }, *multithread, ); } else { run( || { b.iter(move || { future::block_on(async { let mut tasks = Vec::new(); for _ in 0..LIGHT_TASKS { tasks.push(EX.spawn(async {})); } for task in tasks { task.await; } }); }); }, *multithread, ); } }); group.bench_function(format!("{}::spawn_recursively", prefix), |b| { #[allow(clippy::manual_async_fn)] fn go(i: usize) -> impl Future + Send + 'static { async move { if i != 0 { EX.spawn(async move { let fut = go(i - 1).boxed(); fut.await; }) .await; } } } #[allow(clippy::manual_async_fn)] fn go_static(i: usize) -> impl Future + Send + 'static { async move { if i != 0 { STATIC_EX .spawn(async move { let fut = go_static(i - 1).boxed(); fut.await; }) .await; } } } if with_static { run_static( || { b.iter(move || { future::block_on(async { let mut tasks = Vec::new(); for _ in 0..TASKS { tasks.push(STATIC_EX.spawn(go_static(STEPS))); } for task in tasks { task.await; } }); }); }, *multithread, ); } else { run( || { b.iter(move || { future::block_on(async { let mut tasks = Vec::new(); for _ in 0..TASKS { tasks.push(EX.spawn(go(STEPS))); } for task in tasks { task.await; } }); }); }, *multithread, ); } }); group.bench_function(format!("{}::yield_now", prefix), |b| { if with_static { run_static( || { b.iter(move || { future::block_on(async { let mut tasks = Vec::new(); for _ in 0..TASKS { tasks.push(STATIC_EX.spawn(async move { for _ in 0..STEPS { future::yield_now().await; } })); } for task in tasks { task.await; } }); }); }, *multithread, ); } else { run( || { b.iter(move || { future::block_on(async { let mut tasks = Vec::new(); for _ in 0..TASKS { tasks.push(EX.spawn(async move { for _ in 0..STEPS { future::yield_now().await; } })); } for task in tasks { task.await; } }); }); }, *multithread, ); } }); group.bench_function(format!("{}::channels", prefix), |b| { if with_static { run_static( || { b.iter(move || { future::block_on(async { // Create channels. let mut tasks = Vec::new(); let (first_send, first_recv) = async_channel::bounded(1); let mut current_recv = first_recv; for _ in 0..TASKS { let (next_send, next_recv) = async_channel::bounded(1); let current_recv = mem::replace(&mut current_recv, next_recv); tasks.push(STATIC_EX.spawn(async move { // Send a notification on to the next task. for _ in 0..STEPS { current_recv.recv().await.unwrap(); next_send.send(()).await.unwrap(); } })); } for _ in 0..STEPS { first_send.send(()).await.unwrap(); current_recv.recv().await.unwrap(); } for task in tasks { task.await; } }); }); }, *multithread, ) } else { run( || { b.iter(move || { future::block_on(async { // Create channels. let mut tasks = Vec::new(); let (first_send, first_recv) = async_channel::bounded(1); let mut current_recv = first_recv; for _ in 0..TASKS { let (next_send, next_recv) = async_channel::bounded(1); let current_recv = mem::replace(&mut current_recv, next_recv); tasks.push(EX.spawn(async move { // Send a notification on to the next task. for _ in 0..STEPS { current_recv.recv().await.unwrap(); next_send.send(()).await.unwrap(); } })); } for _ in 0..STEPS { first_send.send(()).await.unwrap(); current_recv.recv().await.unwrap(); } for task in tasks { task.await; } }); }); }, *multithread, ) } }); group.bench_function(format!("{}::web_server", prefix), |b| { if with_static { run_static( || { b.iter(move || { future::block_on(async { let (db_send, db_recv) = async_channel::bounded::>( TASKS / 5, ); let mut db_rng = fastrand::Rng::with_seed(0x12345678); let mut web_rng = db_rng.fork(); // This task simulates a database. let db_task = STATIC_EX.spawn(async move { loop { // Wait for a new task. let incoming = match db_recv.recv().await { Ok(incoming) => incoming, Err(_) => break, }; // Process the task. Maybe it takes a while. for _ in 0..db_rng.usize(..10) { future::yield_now().await; } // Send the data back. incoming.send(db_rng.usize(..)).await.ok(); } }); // This task simulates a web server waiting for new tasks. let server_task = STATIC_EX.spawn(async move { for i in 0..TASKS { // Get a new connection. if web_rng.usize(..=16) == 16 { future::yield_now().await; } let mut web_rng = web_rng.fork(); let db_send = db_send.clone(); let task = STATIC_EX.spawn(async move { // Check if the data is cached... if web_rng.bool() { // ...it's in cache! future::yield_now().await; return; } // Otherwise we have to make a DB call or two. for _ in 0..web_rng.usize(STEPS / 2..STEPS) { let (resp_send, resp_recv) = async_channel::bounded(1); db_send.send(resp_send).await.unwrap(); criterion::black_box( resp_recv.recv().await.unwrap(), ); } // Send the data back... for _ in 0..web_rng.usize(3..16) { future::yield_now().await; } }); task.detach(); if i & 16 == 0 { future::yield_now().await; } } }); // Spawn and wait for it to stop. server_task.await; db_task.await; }); }) }, *multithread, ) } else { run( || { b.iter(move || { future::block_on(async { let (db_send, db_recv) = async_channel::bounded::>( TASKS / 5, ); let mut db_rng = fastrand::Rng::with_seed(0x12345678); let mut web_rng = db_rng.fork(); // This task simulates a database. let db_task = EX.spawn(async move { loop { // Wait for a new task. let incoming = match db_recv.recv().await { Ok(incoming) => incoming, Err(_) => break, }; // Process the task. Maybe it takes a while. for _ in 0..db_rng.usize(..10) { future::yield_now().await; } // Send the data back. incoming.send(db_rng.usize(..)).await.ok(); } }); // This task simulates a web server waiting for new tasks. let server_task = EX.spawn(async move { for i in 0..TASKS { // Get a new connection. if web_rng.usize(..=16) == 16 { future::yield_now().await; } let mut web_rng = web_rng.fork(); let db_send = db_send.clone(); let task = EX.spawn(async move { // Check if the data is cached... if web_rng.bool() { // ...it's in cache! future::yield_now().await; return; } // Otherwise we have to make a DB call or two. for _ in 0..web_rng.usize(STEPS / 2..STEPS) { let (resp_send, resp_recv) = async_channel::bounded(1); db_send.send(resp_send).await.unwrap(); criterion::black_box( resp_recv.recv().await.unwrap(), ); } // Send the data back... for _ in 0..web_rng.usize(3..16) { future::yield_now().await; } }); task.detach(); if i & 16 == 0 { future::yield_now().await; } } }); // Spawn and wait for it to stop. server_task.await; db_task.await; }); }) }, *multithread, ) } }); } } } criterion_group!(benches, create, running_benches); criterion_main!(benches); async-executor-1.13.1/examples/000077500000000000000000000000001466710771200163775ustar00rootroot00000000000000async-executor-1.13.1/examples/limit.rs000066400000000000000000000055341466710771200200720ustar00rootroot00000000000000//! An executor where you can only push a limited number of tasks. use async_executor::{Executor, Task}; use async_lock::Semaphore; use std::{future::Future, sync::Arc, time::Duration}; /// An executor where you can only push a limited number of tasks. struct LimitedExecutor { /// Inner running executor. executor: Executor<'static>, /// Semaphore limiting the number of tasks. semaphore: Arc, } impl LimitedExecutor { fn new(max: usize) -> Self { Self { executor: Executor::new(), semaphore: Semaphore::new(max).into(), } } /// Spawn a task, waiting until there is a slot available. async fn spawn(&self, future: F) -> Task where F::Output: Send + 'static, { // Wait for a semaphore permit. let permit = self.semaphore.acquire_arc().await; // Wrap it into a new future. let future = async move { let result = future.await; drop(permit); result }; // Spawn the task. self.executor.spawn(future) } /// Run a future to completion. async fn run(&self, future: F) -> F::Output { self.executor.run(future).await } } fn main() { futures_lite::future::block_on(async { let ex = Arc::new(LimitedExecutor::new(10)); ex.run({ let ex = ex.clone(); async move { // Spawn a bunch of tasks that wait for a while. for i in 0..15 { ex.spawn(async move { async_io::Timer::after(Duration::from_millis(fastrand::u64(1..3))).await; println!("Waiting task #{i} finished!"); }) .await .detach(); } let (start_tx, start_rx) = async_channel::bounded::<()>(1); let mut current_rx = start_rx; // Send the first message. start_tx.send(()).await.unwrap(); // Spawn a bunch of channel tasks that wake eachother up. for i in 0..25 { let (next_tx, next_rx) = async_channel::bounded::<()>(1); ex.spawn(async move { current_rx.recv().await.unwrap(); println!("Channel task {i} woken up!"); next_tx.send(()).await.unwrap(); println!("Channel task {i} finished!"); }) .await .detach(); current_rx = next_rx; } // Wait for the last task to finish. current_rx.recv().await.unwrap(); println!("All tasks finished!"); } }) .await; }); } async-executor-1.13.1/examples/priority.rs000066400000000000000000000041661466710771200206350ustar00rootroot00000000000000//! An executor with task priorities. use std::thread; use async_executor::{Executor, Task}; use futures_lite::{future, prelude::*}; /// Task priority. #[repr(usize)] #[derive(Debug, Clone, Copy)] enum Priority { High = 0, Medium = 1, Low = 2, } /// An executor with task priorities. /// /// Tasks with lower priorities only get polled when there are no tasks with higher priorities. struct PriorityExecutor<'a> { ex: [Executor<'a>; 3], } impl<'a> PriorityExecutor<'a> { /// Creates a new executor. const fn new() -> PriorityExecutor<'a> { PriorityExecutor { ex: [Executor::new(), Executor::new(), Executor::new()], } } /// Spawns a task with the given priority. fn spawn( &self, priority: Priority, future: impl Future + Send + 'a, ) -> Task { self.ex[priority as usize].spawn(future) } /// Runs the executor forever. async fn run(&self) { loop { for _ in 0..200 { let t0 = self.ex[0].tick(); let t1 = self.ex[1].tick(); let t2 = self.ex[2].tick(); // Wait until one of the ticks completes, trying them in order from highest // priority to lowest priority. t0.or(t1).or(t2).await; } // Yield every now and then. future::yield_now().await; } } } fn main() { static EX: PriorityExecutor<'_> = PriorityExecutor::new(); // Spawn a thread running the executor forever. thread::spawn(|| future::block_on(EX.run())); let mut tasks = Vec::new(); for _ in 0..20 { // Choose a random priority. let choice = [Priority::High, Priority::Medium, Priority::Low]; let priority = choice[fastrand::usize(..choice.len())]; // Spawn a task with this priority. tasks.push(EX.spawn(priority, async move { println!("{:?}", priority); future::yield_now().await; println!("{:?}", priority); })); } for task in tasks { future::block_on(task); } } async-executor-1.13.1/src/000077500000000000000000000000001466710771200153505ustar00rootroot00000000000000async-executor-1.13.1/src/lib.rs000066400000000000000000001050731466710771200164720ustar00rootroot00000000000000//! Async executors. //! //! This crate provides two reference executors that trade performance for //! functionality. They should be considered reference executors that are "good //! enough" for most use cases. For more specialized use cases, consider writing //! your own executor on top of [`async-task`]. //! //! [`async-task`]: https://crates.io/crates/async-task //! //! # Examples //! //! ``` //! use async_executor::Executor; //! use futures_lite::future; //! //! // Create a new executor. //! let ex = Executor::new(); //! //! // Spawn a task. //! let task = ex.spawn(async { //! println!("Hello world"); //! }); //! //! // Run the executor until the task completes. //! future::block_on(ex.run(task)); //! ``` #![warn( missing_docs, missing_debug_implementations, rust_2018_idioms, clippy::undocumented_unsafe_blocks )] #![doc( html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" )] #![doc( html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" )] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] use std::fmt; use std::marker::PhantomData; use std::panic::{RefUnwindSafe, UnwindSafe}; use std::rc::Rc; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use std::sync::{Arc, Mutex, RwLock, TryLockError}; use std::task::{Poll, Waker}; use async_task::{Builder, Runnable}; use concurrent_queue::ConcurrentQueue; use futures_lite::{future, prelude::*}; use slab::Slab; #[cfg(feature = "static")] mod static_executors; #[doc(no_inline)] pub use async_task::{FallibleTask, Task}; #[cfg(feature = "static")] #[cfg_attr(docsrs, doc(cfg(any(feature = "static"))))] pub use static_executors::*; /// An async executor. /// /// # Examples /// /// A multi-threaded executor: /// /// ``` /// use async_channel::unbounded; /// use async_executor::Executor; /// use easy_parallel::Parallel; /// use futures_lite::future; /// /// let ex = Executor::new(); /// let (signal, shutdown) = unbounded::<()>(); /// /// Parallel::new() /// // Run four executor threads. /// .each(0..4, |_| future::block_on(ex.run(shutdown.recv()))) /// // Run the main future on the current thread. /// .finish(|| future::block_on(async { /// println!("Hello world!"); /// drop(signal); /// })); /// ``` pub struct Executor<'a> { /// The executor state. state: AtomicPtr, /// Makes the `'a` lifetime invariant. _marker: PhantomData>, } // SAFETY: Executor stores no thread local state that can be accessed via other thread. unsafe impl Send for Executor<'_> {} // SAFETY: Executor internally synchronizes all of it's operations internally. unsafe impl Sync for Executor<'_> {} impl UnwindSafe for Executor<'_> {} impl RefUnwindSafe for Executor<'_> {} impl fmt::Debug for Executor<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { debug_executor(self, "Executor", f) } } impl<'a> Executor<'a> { /// Creates a new executor. /// /// # Examples /// /// ``` /// use async_executor::Executor; /// /// let ex = Executor::new(); /// ``` pub const fn new() -> Executor<'a> { Executor { state: AtomicPtr::new(std::ptr::null_mut()), _marker: PhantomData, } } /// Returns `true` if there are no unfinished tasks. /// /// # Examples /// /// ``` /// use async_executor::Executor; /// /// let ex = Executor::new(); /// assert!(ex.is_empty()); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// assert!(!ex.is_empty()); /// /// assert!(ex.try_tick()); /// assert!(ex.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.state().active.lock().unwrap().is_empty() } /// Spawns a task onto the executor. /// /// # Examples /// /// ``` /// use async_executor::Executor; /// /// let ex = Executor::new(); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// ``` pub fn spawn(&self, future: impl Future + Send + 'a) -> Task { let mut active = self.state().active.lock().unwrap(); // SAFETY: `T` and the future are `Send`. unsafe { self.spawn_inner(future, &mut active) } } /// Spawns many tasks onto the executor. /// /// As opposed to the [`spawn`] method, this locks the executor's inner task lock once and /// spawns all of the tasks in one go. With large amounts of tasks this can improve /// contention. /// /// For very large numbers of tasks the lock is occasionally dropped and re-acquired to /// prevent runner thread starvation. It is assumed that the iterator provided does not /// block; blocking iterators can lock up the internal mutex and therefore the entire /// executor. /// /// ## Example /// /// ``` /// use async_executor::Executor; /// use futures_lite::{stream, prelude::*}; /// use std::future::ready; /// /// # futures_lite::future::block_on(async { /// let mut ex = Executor::new(); /// /// let futures = [ /// ready(1), /// ready(2), /// ready(3) /// ]; /// /// // Spawn all of the futures onto the executor at once. /// let mut tasks = vec![]; /// ex.spawn_many(futures, &mut tasks); /// /// // Await all of them. /// let results = ex.run(async move { /// stream::iter(tasks).then(|x| x).collect::>().await /// }).await; /// assert_eq!(results, [1, 2, 3]); /// # }); /// ``` /// /// [`spawn`]: Executor::spawn pub fn spawn_many + Send + 'a>( &self, futures: impl IntoIterator, handles: &mut impl Extend>, ) { let mut active = Some(self.state().active.lock().unwrap()); // Convert the futures into tasks. let tasks = futures.into_iter().enumerate().map(move |(i, future)| { // SAFETY: `T` and the future are `Send`. let task = unsafe { self.spawn_inner(future, active.as_mut().unwrap()) }; // Yield the lock every once in a while to ease contention. if i.wrapping_sub(1) % 500 == 0 { drop(active.take()); active = Some(self.state().active.lock().unwrap()); } task }); // Push the tasks to the user's collection. handles.extend(tasks); } /// Spawn a future while holding the inner lock. /// /// # Safety /// /// If this is an `Executor`, `F` and `T` must be `Send`. unsafe fn spawn_inner( &self, future: impl Future + 'a, active: &mut Slab, ) -> Task { // Remove the task from the set of active tasks when the future finishes. let entry = active.vacant_entry(); let index = entry.key(); let state = self.state_as_arc(); let future = async move { let _guard = CallOnDrop(move || drop(state.active.lock().unwrap().try_remove(index))); future.await }; // Create the task and register it in the set of active tasks. // // SAFETY: // // If `future` is not `Send`, this must be a `LocalExecutor` as per this // function's unsafe precondition. Since `LocalExecutor` is `!Sync`, // `try_tick`, `tick` and `run` can only be called from the origin // thread of the `LocalExecutor`. Similarly, `spawn` can only be called // from the origin thread, ensuring that `future` and the executor share // the same origin thread. The `Runnable` can be scheduled from other // threads, but because of the above `Runnable` can only be called or // dropped on the origin thread. // // `future` is not `'static`, but we make sure that the `Runnable` does // not outlive `'a`. When the executor is dropped, the `active` field is // drained and all of the `Waker`s are woken. Then, the queue inside of // the `Executor` is drained of all of its runnables. This ensures that // runnables are dropped and this precondition is satisfied. // // `self.schedule()` is `Send`, `Sync` and `'static`, as checked below. // Therefore we do not need to worry about what is done with the // `Waker`. let (runnable, task) = Builder::new() .propagate_panic(true) .spawn_unchecked(|()| future, self.schedule()); entry.insert(runnable.waker()); runnable.schedule(); task } /// Attempts to run a task if at least one is scheduled. /// /// Running a scheduled task means simply polling its future once. /// /// # Examples /// /// ``` /// use async_executor::Executor; /// /// let ex = Executor::new(); /// assert!(!ex.try_tick()); // no tasks to run /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// assert!(ex.try_tick()); // a task was found /// ``` pub fn try_tick(&self) -> bool { self.state().try_tick() } /// Runs a single task. /// /// Running a task means simply polling its future once. /// /// If no tasks are scheduled when this method is called, it will wait until one is scheduled. /// /// # Examples /// /// ``` /// use async_executor::Executor; /// use futures_lite::future; /// /// let ex = Executor::new(); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// future::block_on(ex.tick()); // runs the task /// ``` pub async fn tick(&self) { self.state().tick().await; } /// Runs the executor until the given future completes. /// /// # Examples /// /// ``` /// use async_executor::Executor; /// use futures_lite::future; /// /// let ex = Executor::new(); /// /// let task = ex.spawn(async { 1 + 2 }); /// let res = future::block_on(ex.run(async { task.await * 2 })); /// /// assert_eq!(res, 6); /// ``` pub async fn run(&self, future: impl Future) -> T { self.state().run(future).await } /// Returns a function that schedules a runnable task when it gets woken up. fn schedule(&self) -> impl Fn(Runnable) + Send + Sync + 'static { let state = self.state_as_arc(); // TODO: If possible, push into the current local queue and notify the ticker. move |runnable| { state.queue.push(runnable).unwrap(); state.notify(); } } /// Returns a pointer to the inner state. #[inline] fn state_ptr(&self) -> *const State { #[cold] fn alloc_state(atomic_ptr: &AtomicPtr) -> *mut State { let state = Arc::new(State::new()); // TODO: Switch this to use cast_mut once the MSRV can be bumped past 1.65 let ptr = Arc::into_raw(state) as *mut State; if let Err(actual) = atomic_ptr.compare_exchange( std::ptr::null_mut(), ptr, Ordering::AcqRel, Ordering::Acquire, ) { // SAFETY: This was just created from Arc::into_raw. drop(unsafe { Arc::from_raw(ptr) }); actual } else { ptr } } let mut ptr = self.state.load(Ordering::Acquire); if ptr.is_null() { ptr = alloc_state(&self.state); } ptr } /// Returns a reference to the inner state. #[inline] fn state(&self) -> &State { // SAFETY: So long as an Executor lives, it's state pointer will always be valid // when accessed through state_ptr. unsafe { &*self.state_ptr() } } // Clones the inner state Arc #[inline] fn state_as_arc(&self) -> Arc { // SAFETY: So long as an Executor lives, it's state pointer will always be a valid // Arc when accessed through state_ptr. let arc = unsafe { Arc::from_raw(self.state_ptr()) }; let clone = arc.clone(); std::mem::forget(arc); clone } } impl Drop for Executor<'_> { fn drop(&mut self) { let ptr = *self.state.get_mut(); if ptr.is_null() { return; } // SAFETY: As ptr is not null, it was allocated via Arc::new and converted // via Arc::into_raw in state_ptr. let state = unsafe { Arc::from_raw(ptr) }; let mut active = state.active.lock().unwrap_or_else(|e| e.into_inner()); for w in active.drain() { w.wake(); } drop(active); while state.queue.pop().is_ok() {} } } impl<'a> Default for Executor<'a> { fn default() -> Executor<'a> { Executor::new() } } /// A thread-local executor. /// /// The executor can only be run on the thread that created it. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// use futures_lite::future; /// /// let local_ex = LocalExecutor::new(); /// /// future::block_on(local_ex.run(async { /// println!("Hello world!"); /// })); /// ``` pub struct LocalExecutor<'a> { /// The inner executor. inner: Executor<'a>, /// Makes the type `!Send` and `!Sync`. _marker: PhantomData>, } impl UnwindSafe for LocalExecutor<'_> {} impl RefUnwindSafe for LocalExecutor<'_> {} impl fmt::Debug for LocalExecutor<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { debug_executor(&self.inner, "LocalExecutor", f) } } impl<'a> LocalExecutor<'a> { /// Creates a single-threaded executor. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// /// let local_ex = LocalExecutor::new(); /// ``` pub const fn new() -> LocalExecutor<'a> { LocalExecutor { inner: Executor::new(), _marker: PhantomData, } } /// Returns `true` if there are no unfinished tasks. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// /// let local_ex = LocalExecutor::new(); /// assert!(local_ex.is_empty()); /// /// let task = local_ex.spawn(async { /// println!("Hello world"); /// }); /// assert!(!local_ex.is_empty()); /// /// assert!(local_ex.try_tick()); /// assert!(local_ex.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.inner().is_empty() } /// Spawns a task onto the executor. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// /// let local_ex = LocalExecutor::new(); /// /// let task = local_ex.spawn(async { /// println!("Hello world"); /// }); /// ``` pub fn spawn(&self, future: impl Future + 'a) -> Task { let mut active = self.inner().state().active.lock().unwrap(); // SAFETY: This executor is not thread safe, so the future and its result // cannot be sent to another thread. unsafe { self.inner().spawn_inner(future, &mut active) } } /// Spawns many tasks onto the executor. /// /// As opposed to the [`spawn`] method, this locks the executor's inner task lock once and /// spawns all of the tasks in one go. With large amounts of tasks this can improve /// contention. /// /// It is assumed that the iterator provided does not block; blocking iterators can lock up /// the internal mutex and therefore the entire executor. Unlike [`Executor::spawn`], the /// mutex is not released, as there are no other threads that can poll this executor. /// /// ## Example /// /// ``` /// use async_executor::LocalExecutor; /// use futures_lite::{stream, prelude::*}; /// use std::future::ready; /// /// # futures_lite::future::block_on(async { /// let mut ex = LocalExecutor::new(); /// /// let futures = [ /// ready(1), /// ready(2), /// ready(3) /// ]; /// /// // Spawn all of the futures onto the executor at once. /// let mut tasks = vec![]; /// ex.spawn_many(futures, &mut tasks); /// /// // Await all of them. /// let results = ex.run(async move { /// stream::iter(tasks).then(|x| x).collect::>().await /// }).await; /// assert_eq!(results, [1, 2, 3]); /// # }); /// ``` /// /// [`spawn`]: LocalExecutor::spawn /// [`Executor::spawn_many`]: Executor::spawn_many pub fn spawn_many + 'a>( &self, futures: impl IntoIterator, handles: &mut impl Extend>, ) { let mut active = self.inner().state().active.lock().unwrap(); // Convert all of the futures to tasks. let tasks = futures.into_iter().map(|future| { // SAFETY: This executor is not thread safe, so the future and its result // cannot be sent to another thread. unsafe { self.inner().spawn_inner(future, &mut active) } // As only one thread can spawn or poll tasks at a time, there is no need // to release lock contention here. }); // Push them to the user's collection. handles.extend(tasks); } /// Attempts to run a task if at least one is scheduled. /// /// Running a scheduled task means simply polling its future once. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// /// let ex = LocalExecutor::new(); /// assert!(!ex.try_tick()); // no tasks to run /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// assert!(ex.try_tick()); // a task was found /// ``` pub fn try_tick(&self) -> bool { self.inner().try_tick() } /// Runs a single task. /// /// Running a task means simply polling its future once. /// /// If no tasks are scheduled when this method is called, it will wait until one is scheduled. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// use futures_lite::future; /// /// let ex = LocalExecutor::new(); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// future::block_on(ex.tick()); // runs the task /// ``` pub async fn tick(&self) { self.inner().tick().await } /// Runs the executor until the given future completes. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// use futures_lite::future; /// /// let local_ex = LocalExecutor::new(); /// /// let task = local_ex.spawn(async { 1 + 2 }); /// let res = future::block_on(local_ex.run(async { task.await * 2 })); /// /// assert_eq!(res, 6); /// ``` pub async fn run(&self, future: impl Future) -> T { self.inner().run(future).await } /// Returns a reference to the inner executor. fn inner(&self) -> &Executor<'a> { &self.inner } } impl<'a> Default for LocalExecutor<'a> { fn default() -> LocalExecutor<'a> { LocalExecutor::new() } } /// The state of a executor. struct State { /// The global queue. queue: ConcurrentQueue, /// Local queues created by runners. local_queues: RwLock>>>, /// Set to `true` when a sleeping ticker is notified or no tickers are sleeping. notified: AtomicBool, /// A list of sleeping tickers. sleepers: Mutex, /// Currently active tasks. active: Mutex>, } impl State { /// Creates state for a new executor. const fn new() -> State { State { queue: ConcurrentQueue::unbounded(), local_queues: RwLock::new(Vec::new()), notified: AtomicBool::new(true), sleepers: Mutex::new(Sleepers { count: 0, wakers: Vec::new(), free_ids: Vec::new(), }), active: Mutex::new(Slab::new()), } } /// Notifies a sleeping ticker. #[inline] fn notify(&self) { if self .notified .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .is_ok() { let waker = self.sleepers.lock().unwrap().notify(); if let Some(w) = waker { w.wake(); } } } pub(crate) fn try_tick(&self) -> bool { match self.queue.pop() { Err(_) => false, Ok(runnable) => { // Notify another ticker now to pick up where this ticker left off, just in case // running the task takes a long time. self.notify(); // Run the task. runnable.run(); true } } } pub(crate) async fn tick(&self) { let runnable = Ticker::new(self).runnable().await; runnable.run(); } pub async fn run(&self, future: impl Future) -> T { let mut runner = Runner::new(self); let mut rng = fastrand::Rng::new(); // A future that runs tasks forever. let run_forever = async { loop { for _ in 0..200 { let runnable = runner.runnable(&mut rng).await; runnable.run(); } future::yield_now().await; } }; // Run `future` and `run_forever` concurrently until `future` completes. future.or(run_forever).await } } /// A list of sleeping tickers. struct Sleepers { /// Number of sleeping tickers (both notified and unnotified). count: usize, /// IDs and wakers of sleeping unnotified tickers. /// /// A sleeping ticker is notified when its waker is missing from this list. wakers: Vec<(usize, Waker)>, /// Reclaimed IDs. free_ids: Vec, } impl Sleepers { /// Inserts a new sleeping ticker. fn insert(&mut self, waker: &Waker) -> usize { let id = match self.free_ids.pop() { Some(id) => id, None => self.count + 1, }; self.count += 1; self.wakers.push((id, waker.clone())); id } /// Re-inserts a sleeping ticker's waker if it was notified. /// /// Returns `true` if the ticker was notified. fn update(&mut self, id: usize, waker: &Waker) -> bool { for item in &mut self.wakers { if item.0 == id { item.1.clone_from(waker); return false; } } self.wakers.push((id, waker.clone())); true } /// Removes a previously inserted sleeping ticker. /// /// Returns `true` if the ticker was notified. fn remove(&mut self, id: usize) -> bool { self.count -= 1; self.free_ids.push(id); for i in (0..self.wakers.len()).rev() { if self.wakers[i].0 == id { self.wakers.remove(i); return false; } } true } /// Returns `true` if a sleeping ticker is notified or no tickers are sleeping. fn is_notified(&self) -> bool { self.count == 0 || self.count > self.wakers.len() } /// Returns notification waker for a sleeping ticker. /// /// If a ticker was notified already or there are no tickers, `None` will be returned. fn notify(&mut self) -> Option { if self.wakers.len() == self.count { self.wakers.pop().map(|item| item.1) } else { None } } } /// Runs task one by one. struct Ticker<'a> { /// The executor state. state: &'a State, /// Set to a non-zero sleeper ID when in sleeping state. /// /// States a ticker can be in: /// 1) Woken. /// 2a) Sleeping and unnotified. /// 2b) Sleeping and notified. sleeping: usize, } impl Ticker<'_> { /// Creates a ticker. fn new(state: &State) -> Ticker<'_> { Ticker { state, sleeping: 0 } } /// Moves the ticker into sleeping and unnotified state. /// /// Returns `false` if the ticker was already sleeping and unnotified. fn sleep(&mut self, waker: &Waker) -> bool { let mut sleepers = self.state.sleepers.lock().unwrap(); match self.sleeping { // Move to sleeping state. 0 => { self.sleeping = sleepers.insert(waker); } // Already sleeping, check if notified. id => { if !sleepers.update(id, waker) { return false; } } } self.state .notified .store(sleepers.is_notified(), Ordering::Release); true } /// Moves the ticker into woken state. fn wake(&mut self) { if self.sleeping != 0 { let mut sleepers = self.state.sleepers.lock().unwrap(); sleepers.remove(self.sleeping); self.state .notified .store(sleepers.is_notified(), Ordering::Release); } self.sleeping = 0; } /// Waits for the next runnable task to run. async fn runnable(&mut self) -> Runnable { self.runnable_with(|| self.state.queue.pop().ok()).await } /// Waits for the next runnable task to run, given a function that searches for a task. async fn runnable_with(&mut self, mut search: impl FnMut() -> Option) -> Runnable { future::poll_fn(|cx| { loop { match search() { None => { // Move to sleeping and unnotified state. if !self.sleep(cx.waker()) { // If already sleeping and unnotified, return. return Poll::Pending; } } Some(r) => { // Wake up. self.wake(); // Notify another ticker now to pick up where this ticker left off, just in // case running the task takes a long time. self.state.notify(); return Poll::Ready(r); } } } }) .await } } impl Drop for Ticker<'_> { fn drop(&mut self) { // If this ticker is in sleeping state, it must be removed from the sleepers list. if self.sleeping != 0 { let mut sleepers = self.state.sleepers.lock().unwrap(); let notified = sleepers.remove(self.sleeping); self.state .notified .store(sleepers.is_notified(), Ordering::Release); // If this ticker was notified, then notify another ticker. if notified { drop(sleepers); self.state.notify(); } } } } /// A worker in a work-stealing executor. /// /// This is just a ticker that also has an associated local queue for improved cache locality. struct Runner<'a> { /// The executor state. state: &'a State, /// Inner ticker. ticker: Ticker<'a>, /// The local queue. local: Arc>, /// Bumped every time a runnable task is found. ticks: usize, } impl Runner<'_> { /// Creates a runner and registers it in the executor state. fn new(state: &State) -> Runner<'_> { let runner = Runner { state, ticker: Ticker::new(state), local: Arc::new(ConcurrentQueue::bounded(512)), ticks: 0, }; state .local_queues .write() .unwrap() .push(runner.local.clone()); runner } /// Waits for the next runnable task to run. async fn runnable(&mut self, rng: &mut fastrand::Rng) -> Runnable { let runnable = self .ticker .runnable_with(|| { // Try the local queue. if let Ok(r) = self.local.pop() { return Some(r); } // Try stealing from the global queue. if let Ok(r) = self.state.queue.pop() { steal(&self.state.queue, &self.local); return Some(r); } // Try stealing from other runners. let local_queues = self.state.local_queues.read().unwrap(); // Pick a random starting point in the iterator list and rotate the list. let n = local_queues.len(); let start = rng.usize(..n); let iter = local_queues .iter() .chain(local_queues.iter()) .skip(start) .take(n); // Remove this runner's local queue. let iter = iter.filter(|local| !Arc::ptr_eq(local, &self.local)); // Try stealing from each local queue in the list. for local in iter { steal(local, &self.local); if let Ok(r) = self.local.pop() { return Some(r); } } None }) .await; // Bump the tick counter. self.ticks = self.ticks.wrapping_add(1); if self.ticks % 64 == 0 { // Steal tasks from the global queue to ensure fair task scheduling. steal(&self.state.queue, &self.local); } runnable } } impl Drop for Runner<'_> { fn drop(&mut self) { // Remove the local queue. self.state .local_queues .write() .unwrap() .retain(|local| !Arc::ptr_eq(local, &self.local)); // Re-schedule remaining tasks in the local queue. while let Ok(r) = self.local.pop() { r.schedule(); } } } /// Steals some items from one queue into another. fn steal(src: &ConcurrentQueue, dest: &ConcurrentQueue) { // Half of `src`'s length rounded up. let mut count = (src.len() + 1) / 2; if count > 0 { // Don't steal more than fits into the queue. if let Some(cap) = dest.capacity() { count = count.min(cap - dest.len()); } // Steal tasks. for _ in 0..count { if let Ok(t) = src.pop() { assert!(dest.push(t).is_ok()); } else { break; } } } } /// Debug implementation for `Executor` and `LocalExecutor`. fn debug_executor(executor: &Executor<'_>, name: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Get a reference to the state. let ptr = executor.state.load(Ordering::Acquire); if ptr.is_null() { // The executor has not been initialized. struct Uninitialized; impl fmt::Debug for Uninitialized { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("") } } return f.debug_tuple(name).field(&Uninitialized).finish(); } // SAFETY: If the state pointer is not null, it must have been // allocated properly by Arc::new and converted via Arc::into_raw // in state_ptr. let state = unsafe { &*ptr }; debug_state(state, name, f) } /// Debug implementation for `Executor` and `LocalExecutor`. fn debug_state(state: &State, name: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result { /// Debug wrapper for the number of active tasks. struct ActiveTasks<'a>(&'a Mutex>); impl fmt::Debug for ActiveTasks<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.0.try_lock() { Ok(lock) => fmt::Debug::fmt(&lock.len(), f), Err(TryLockError::WouldBlock) => f.write_str(""), Err(TryLockError::Poisoned(_)) => f.write_str(""), } } } /// Debug wrapper for the local runners. struct LocalRunners<'a>(&'a RwLock>>>); impl fmt::Debug for LocalRunners<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.0.try_read() { Ok(lock) => f .debug_list() .entries(lock.iter().map(|queue| queue.len())) .finish(), Err(TryLockError::WouldBlock) => f.write_str(""), Err(TryLockError::Poisoned(_)) => f.write_str(""), } } } /// Debug wrapper for the sleepers. struct SleepCount<'a>(&'a Mutex); impl fmt::Debug for SleepCount<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.0.try_lock() { Ok(lock) => fmt::Debug::fmt(&lock.count, f), Err(TryLockError::WouldBlock) => f.write_str(""), Err(TryLockError::Poisoned(_)) => f.write_str(""), } } } f.debug_struct(name) .field("active", &ActiveTasks(&state.active)) .field("global_tasks", &state.queue.len()) .field("local_runners", &LocalRunners(&state.local_queues)) .field("sleepers", &SleepCount(&state.sleepers)) .finish() } /// Runs a closure when dropped. struct CallOnDrop(F); impl Drop for CallOnDrop { fn drop(&mut self) { (self.0)(); } } fn _ensure_send_and_sync() { use futures_lite::future::pending; fn is_send(_: T) {} fn is_sync(_: T) {} fn is_static(_: T) {} is_send::>(Executor::new()); is_sync::>(Executor::new()); let ex = Executor::new(); is_send(ex.run(pending::<()>())); is_sync(ex.run(pending::<()>())); is_send(ex.tick()); is_sync(ex.tick()); is_send(ex.schedule()); is_sync(ex.schedule()); is_static(ex.schedule()); /// ```compile_fail /// use async_executor::LocalExecutor; /// use futures_lite::future::pending; /// /// fn is_send(_: T) {} /// fn is_sync(_: T) {} /// /// is_send::>(LocalExecutor::new()); /// is_sync::>(LocalExecutor::new()); /// /// let ex = LocalExecutor::new(); /// is_send(ex.run(pending::<()>())); /// is_sync(ex.run(pending::<()>())); /// is_send(ex.tick()); /// is_sync(ex.tick()); /// ``` fn _negative_test() {} } async-executor-1.13.1/src/static_executors.rs000066400000000000000000000367001466710771200213140ustar00rootroot00000000000000use crate::{debug_state, Executor, LocalExecutor, State}; use async_task::{Builder, Runnable, Task}; use slab::Slab; use std::{ cell::UnsafeCell, fmt, future::Future, marker::PhantomData, panic::{RefUnwindSafe, UnwindSafe}, }; impl Executor<'static> { /// Consumes the [`Executor`] and intentionally leaks it. /// /// Largely equivalent to calling `Box::leak(Box::new(executor))`, but the produced /// [`StaticExecutor`]'s functions are optimized to require fewer synchronizing operations /// when spawning, running, and finishing tasks. /// /// `StaticExecutor` cannot be converted back into a `Executor`, so this operation is /// irreversible without the use of unsafe. /// /// # Example /// /// ``` /// use async_executor::Executor; /// use futures_lite::future; /// /// let ex = Executor::new().leak(); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// /// future::block_on(ex.run(task)); /// ``` pub fn leak(self) -> &'static StaticExecutor { let ptr = self.state_ptr(); // SAFETY: So long as an Executor lives, it's state pointer will always be valid // when accessed through state_ptr. This executor will live for the full 'static // lifetime so this isn't an arbitrary lifetime extension. let state: &'static State = unsafe { &*ptr }; std::mem::forget(self); let mut active = state.active.lock().unwrap(); if !active.is_empty() { // Reschedule all of the active tasks. for waker in active.drain() { waker.wake(); } // Overwrite to ensure that the slab is deallocated. *active = Slab::new(); } // SAFETY: StaticExecutor has the same memory layout as State as it's repr(transparent). // The lifetime is not altered: 'static -> 'static. let static_executor: &'static StaticExecutor = unsafe { std::mem::transmute(state) }; static_executor } } impl LocalExecutor<'static> { /// Consumes the [`LocalExecutor`] and intentionally leaks it. /// /// Largely equivalent to calling `Box::leak(Box::new(executor))`, but the produced /// [`StaticLocalExecutor`]'s functions are optimized to require fewer synchronizing operations /// when spawning, running, and finishing tasks. /// /// `StaticLocalExecutor` cannot be converted back into a `Executor`, so this operation is /// irreversible without the use of unsafe. /// /// # Example /// /// ``` /// use async_executor::LocalExecutor; /// use futures_lite::future; /// /// let ex = LocalExecutor::new().leak(); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// /// future::block_on(ex.run(task)); /// ``` pub fn leak(self) -> &'static StaticLocalExecutor { let ptr = self.inner.state_ptr(); // SAFETY: So long as a LocalExecutor lives, it's state pointer will always be valid // when accessed through state_ptr. This executor will live for the full 'static // lifetime so this isn't an arbitrary lifetime extension. let state: &'static State = unsafe { &*ptr }; std::mem::forget(self); let mut active = state.active.lock().unwrap(); if !active.is_empty() { // Reschedule all of the active tasks. for waker in active.drain() { waker.wake(); } // Overwrite to ensure that the slab is deallocated. *active = Slab::new(); } // SAFETY: StaticLocalExecutor has the same memory layout as State as it's repr(transparent). // The lifetime is not altered: 'static -> 'static. let static_executor: &'static StaticLocalExecutor = unsafe { std::mem::transmute(state) }; static_executor } } /// A static-lifetimed async [`Executor`]. /// /// This is primarily intended to be used in [`static`] variables, or types intended to be used, or can be created in non-static /// contexts via [`Executor::leak`]. /// /// Spawning, running, and finishing tasks are optimized with the assumption that the executor will never be `Drop`'ed. /// A static executor may require signficantly less overhead in both single-threaded and mulitthreaded use cases. /// /// As this type does not implement `Drop`, losing the handle to the executor or failing /// to consistently drive the executor with [`StaticExecutor::tick`] or /// [`StaticExecutor::run`] will cause the all spawned tasks to permanently leak. Any /// tasks at the time will not be cancelled. /// /// [`static`]: https://doc.rust-lang.org/std/keyword.static.html #[repr(transparent)] pub struct StaticExecutor { state: State, } // SAFETY: Executor stores no thread local state that can be accessed via other thread. unsafe impl Send for StaticExecutor {} // SAFETY: Executor internally synchronizes all of it's operations internally. unsafe impl Sync for StaticExecutor {} impl UnwindSafe for StaticExecutor {} impl RefUnwindSafe for StaticExecutor {} impl fmt::Debug for StaticExecutor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { debug_state(&self.state, "StaticExecutor", f) } } impl StaticExecutor { /// Creates a new StaticExecutor. /// /// # Examples /// /// ``` /// use async_executor::StaticExecutor; /// /// static EXECUTOR: StaticExecutor = StaticExecutor::new(); /// ``` pub const fn new() -> Self { Self { state: State::new(), } } /// Spawns a task onto the executor. /// /// Note: unlike [`Executor::spawn`], this function requires being called with a `'static` /// borrow on the executor. /// /// # Examples /// /// ``` /// use async_executor::StaticExecutor; /// /// static EXECUTOR: StaticExecutor = StaticExecutor::new(); /// /// let task = EXECUTOR.spawn(async { /// println!("Hello world"); /// }); /// ``` pub fn spawn( &'static self, future: impl Future + Send + 'static, ) -> Task { let (runnable, task) = Builder::new() .propagate_panic(true) .spawn(|()| future, self.schedule()); runnable.schedule(); task } /// Spawns a non-`'static` task onto the executor. /// /// ## Safety /// /// The caller must ensure that the returned task terminates /// or is cancelled before the end of 'a. pub unsafe fn spawn_scoped<'a, T: Send + 'a>( &'static self, future: impl Future + Send + 'a, ) -> Task { // SAFETY: // // - `future` is `Send` // - `future` is not `'static`, but the caller guarantees that the // task, and thus its `Runnable` must not live longer than `'a`. // - `self.schedule()` is `Send`, `Sync` and `'static`, as checked below. // Therefore we do not need to worry about what is done with the // `Waker`. let (runnable, task) = unsafe { Builder::new() .propagate_panic(true) .spawn_unchecked(|()| future, self.schedule()) }; runnable.schedule(); task } /// Attempts to run a task if at least one is scheduled. /// /// Running a scheduled task means simply polling its future once. /// /// # Examples /// /// ``` /// use async_executor::StaticExecutor; /// /// static EXECUTOR: StaticExecutor = StaticExecutor::new(); /// /// assert!(!EXECUTOR.try_tick()); // no tasks to run /// /// let task = EXECUTOR.spawn(async { /// println!("Hello world"); /// }); /// /// assert!(EXECUTOR.try_tick()); // a task was found /// ``` pub fn try_tick(&self) -> bool { self.state.try_tick() } /// Runs a single task. /// /// Running a task means simply polling its future once. /// /// If no tasks are scheduled when this method is called, it will wait until one is scheduled. /// /// # Examples /// /// ``` /// use async_executor::StaticExecutor; /// use futures_lite::future; /// /// static EXECUTOR: StaticExecutor = StaticExecutor::new(); /// /// let task = EXECUTOR.spawn(async { /// println!("Hello world"); /// }); /// /// future::block_on(EXECUTOR.tick()); // runs the task /// ``` pub async fn tick(&self) { self.state.tick().await; } /// Runs the executor until the given future completes. /// /// # Examples /// /// ``` /// use async_executor::StaticExecutor; /// use futures_lite::future; /// /// static EXECUTOR: StaticExecutor = StaticExecutor::new(); /// /// let task = EXECUTOR.spawn(async { 1 + 2 }); /// let res = future::block_on(EXECUTOR.run(async { task.await * 2 })); /// /// assert_eq!(res, 6); /// ``` pub async fn run(&self, future: impl Future) -> T { self.state.run(future).await } /// Returns a function that schedules a runnable task when it gets woken up. fn schedule(&'static self) -> impl Fn(Runnable) + Send + Sync + 'static { let state: &'static State = &self.state; // TODO: If possible, push into the current local queue and notify the ticker. move |runnable| { state.queue.push(runnable).unwrap(); state.notify(); } } } impl Default for StaticExecutor { fn default() -> Self { Self::new() } } /// A static async [`LocalExecutor`] created from [`LocalExecutor::leak`]. /// /// This is primarily intended to be used in [`thread_local`] variables, or can be created in non-static /// contexts via [`LocalExecutor::leak`]. /// /// Spawning, running, and finishing tasks are optimized with the assumption that the executor will never be `Drop`'ed. /// A static executor may require signficantly less overhead in both single-threaded and mulitthreaded use cases. /// /// As this type does not implement `Drop`, losing the handle to the executor or failing /// to consistently drive the executor with [`StaticLocalExecutor::tick`] or /// [`StaticLocalExecutor::run`] will cause the all spawned tasks to permanently leak. Any /// tasks at the time will not be cancelled. /// /// [`thread_local]: https://doc.rust-lang.org/std/macro.thread_local.html #[repr(transparent)] pub struct StaticLocalExecutor { state: State, marker_: PhantomData>, } impl UnwindSafe for StaticLocalExecutor {} impl RefUnwindSafe for StaticLocalExecutor {} impl fmt::Debug for StaticLocalExecutor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { debug_state(&self.state, "StaticLocalExecutor", f) } } impl StaticLocalExecutor { /// Creates a new StaticLocalExecutor. /// /// # Examples /// /// ``` /// use async_executor::StaticLocalExecutor; /// /// thread_local! { /// static EXECUTOR: StaticLocalExecutor = StaticLocalExecutor::new(); /// } /// ``` pub const fn new() -> Self { Self { state: State::new(), marker_: PhantomData, } } /// Spawns a task onto the executor. /// /// Note: unlike [`LocalExecutor::spawn`], this function requires being called with a `'static` /// borrow on the executor. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// /// let ex = LocalExecutor::new().leak(); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// ``` pub fn spawn(&'static self, future: impl Future + 'static) -> Task { let (runnable, task) = Builder::new() .propagate_panic(true) .spawn_local(|()| future, self.schedule()); runnable.schedule(); task } /// Spawns a non-`'static` task onto the executor. /// /// ## Safety /// /// The caller must ensure that the returned task terminates /// or is cancelled before the end of 'a. pub unsafe fn spawn_scoped<'a, T: 'a>( &'static self, future: impl Future + 'a, ) -> Task { // SAFETY: // // - `future` is not `Send` but `StaticLocalExecutor` is `!Sync`, // `try_tick`, `tick` and `run` can only be called from the origin // thread of the `StaticLocalExecutor`. Similarly, `spawn_scoped` can only // be called from the origin thread, ensuring that `future` and the executor // share the same origin thread. The `Runnable` can be scheduled from other // threads, but because of the above `Runnable` can only be called or // dropped on the origin thread. // - `future` is not `'static`, but the caller guarantees that the // task, and thus its `Runnable` must not live longer than `'a`. // - `self.schedule()` is `Send`, `Sync` and `'static`, as checked below. // Therefore we do not need to worry about what is done with the // `Waker`. let (runnable, task) = unsafe { Builder::new() .propagate_panic(true) .spawn_unchecked(|()| future, self.schedule()) }; runnable.schedule(); task } /// Attempts to run a task if at least one is scheduled. /// /// Running a scheduled task means simply polling its future once. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// /// let ex = LocalExecutor::new().leak(); /// assert!(!ex.try_tick()); // no tasks to run /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// assert!(ex.try_tick()); // a task was found /// ``` pub fn try_tick(&self) -> bool { self.state.try_tick() } /// Runs a single task. /// /// Running a task means simply polling its future once. /// /// If no tasks are scheduled when this method is called, it will wait until one is scheduled. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// use futures_lite::future; /// /// let ex = LocalExecutor::new().leak(); /// /// let task = ex.spawn(async { /// println!("Hello world"); /// }); /// future::block_on(ex.tick()); // runs the task /// ``` pub async fn tick(&self) { self.state.tick().await; } /// Runs the executor until the given future completes. /// /// # Examples /// /// ``` /// use async_executor::LocalExecutor; /// use futures_lite::future; /// /// let ex = LocalExecutor::new().leak(); /// /// let task = ex.spawn(async { 1 + 2 }); /// let res = future::block_on(ex.run(async { task.await * 2 })); /// /// assert_eq!(res, 6); /// ``` pub async fn run(&self, future: impl Future) -> T { self.state.run(future).await } /// Returns a function that schedules a runnable task when it gets woken up. fn schedule(&'static self) -> impl Fn(Runnable) + Send + Sync + 'static { let state: &'static State = &self.state; // TODO: If possible, push into the current local queue and notify the ticker. move |runnable| { state.queue.push(runnable).unwrap(); state.notify(); } } } impl Default for StaticLocalExecutor { fn default() -> Self { Self::new() } } async-executor-1.13.1/tests/000077500000000000000000000000001466710771200157235ustar00rootroot00000000000000async-executor-1.13.1/tests/different_executors.rs000066400000000000000000000020151466710771200223360ustar00rootroot00000000000000use async_executor::LocalExecutor; use futures_lite::future::{block_on, pending, poll_once}; use futures_lite::pin; use std::cell::Cell; #[test] fn shared_queue_slot() { block_on(async { let was_polled = Cell::new(false); let future = async { was_polled.set(true); pending::<()>().await; }; let ex1 = LocalExecutor::new(); let ex2 = LocalExecutor::new(); // Start the futures for running forever. let (run1, run2) = (ex1.run(pending::<()>()), ex2.run(pending::<()>())); pin!(run1); pin!(run2); assert!(poll_once(run1.as_mut()).await.is_none()); assert!(poll_once(run2.as_mut()).await.is_none()); // Spawn the future on executor one and then poll executor two. ex1.spawn(future).detach(); assert!(poll_once(run2).await.is_none()); assert!(!was_polled.get()); // Poll the first one. assert!(poll_once(run1).await.is_none()); assert!(was_polled.get()); }); } async-executor-1.13.1/tests/drop.rs000066400000000000000000000067501466710771200172450ustar00rootroot00000000000000#[cfg(not(miri))] use std::mem; use std::panic::catch_unwind; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::task::{Poll, Waker}; use async_executor::{Executor, Task}; use futures_lite::future; use once_cell::sync::Lazy; #[test] fn executor_cancels_everything() { static DROP: AtomicUsize = AtomicUsize::new(0); static WAKER: Lazy>> = Lazy::new(Default::default); let ex = Executor::new(); let task = ex.spawn(async { let _guard = CallOnDrop(|| { DROP.fetch_add(1, Ordering::SeqCst); }); future::poll_fn(|cx| { *WAKER.lock().unwrap() = Some(cx.waker().clone()); Poll::Pending::<()> }) .await; }); future::block_on(ex.tick()); assert!(WAKER.lock().unwrap().is_some()); assert_eq!(DROP.load(Ordering::SeqCst), 0); drop(ex); assert_eq!(DROP.load(Ordering::SeqCst), 1); assert!(catch_unwind(|| future::block_on(task)).is_err()); assert_eq!(DROP.load(Ordering::SeqCst), 1); } #[cfg(not(miri))] #[test] fn leaked_executor_leaks_everything() { static DROP: AtomicUsize = AtomicUsize::new(0); static WAKER: Lazy>> = Lazy::new(Default::default); let ex = Executor::new(); let task = ex.spawn(async { let _guard = CallOnDrop(|| { DROP.fetch_add(1, Ordering::SeqCst); }); future::poll_fn(|cx| { *WAKER.lock().unwrap() = Some(cx.waker().clone()); Poll::Pending::<()> }) .await; }); future::block_on(ex.tick()); assert!(WAKER.lock().unwrap().is_some()); assert_eq!(DROP.load(Ordering::SeqCst), 0); mem::forget(ex); assert_eq!(DROP.load(Ordering::SeqCst), 0); assert!(future::block_on(future::poll_once(task)).is_none()); assert_eq!(DROP.load(Ordering::SeqCst), 0); } #[test] fn await_task_after_dropping_executor() { let s: String = "hello".into(); let ex = Executor::new(); let task: Task<&str> = ex.spawn(async { &*s }); assert!(ex.try_tick()); drop(ex); assert_eq!(future::block_on(task), "hello"); drop(s); } #[test] fn drop_executor_and_then_drop_finished_task() { static DROP: AtomicUsize = AtomicUsize::new(0); let ex = Executor::new(); let task = ex.spawn(async { CallOnDrop(|| { DROP.fetch_add(1, Ordering::SeqCst); }) }); assert!(ex.try_tick()); assert_eq!(DROP.load(Ordering::SeqCst), 0); drop(ex); assert_eq!(DROP.load(Ordering::SeqCst), 0); drop(task); assert_eq!(DROP.load(Ordering::SeqCst), 1); } #[test] fn drop_finished_task_and_then_drop_executor() { static DROP: AtomicUsize = AtomicUsize::new(0); let ex = Executor::new(); let task = ex.spawn(async { CallOnDrop(|| { DROP.fetch_add(1, Ordering::SeqCst); }) }); assert!(ex.try_tick()); assert_eq!(DROP.load(Ordering::SeqCst), 0); drop(task); assert_eq!(DROP.load(Ordering::SeqCst), 1); drop(ex); assert_eq!(DROP.load(Ordering::SeqCst), 1); } #[test] fn iterator_panics_mid_run() { let ex = Executor::new(); let panic = std::panic::catch_unwind(|| { let mut handles = vec![]; ex.spawn_many( (0..50).map(|i| if i == 25 { panic!() } else { future::ready(i) }), &mut handles, ) }); assert!(panic.is_err()); } struct CallOnDrop(F); impl Drop for CallOnDrop { fn drop(&mut self) { (self.0)(); } } async-executor-1.13.1/tests/larger_tasks.rs000066400000000000000000000046711466710771200207620ustar00rootroot00000000000000//! Test for larger tasks. use async_executor::Executor; use futures_lite::future::{self, block_on}; use futures_lite::prelude::*; use std::sync::Arc; use std::thread; use std::time::Duration; fn do_run>(mut f: impl FnMut(Arc>) -> Fut) { // This should not run for longer than two minutes. #[cfg(not(miri))] let _stop_timeout = { let (stop_timeout, stopper) = async_channel::bounded::<()>(1); thread::spawn(move || { block_on(async move { let timeout = async { async_io::Timer::after(Duration::from_secs(2 * 60)).await; eprintln!("test timed out after 2m"); std::process::exit(1) }; let _ = stopper.recv().or(timeout).await; }) }); stop_timeout }; let ex = Arc::new(Executor::new()); // Test 1: Use the `run` command. block_on(ex.run(f(ex.clone()))); // Test 2: Loop on `tick`. block_on(async { let ticker = async { loop { ex.tick().await; } }; f(ex.clone()).or(ticker).await }); // Test 3: Run on many threads. thread::scope(|scope| { let (_signal, shutdown) = async_channel::bounded::<()>(1); for _ in 0..16 { let shutdown = shutdown.clone(); let ex = &ex; scope.spawn(move || block_on(ex.run(shutdown.recv()))); } block_on(f(ex.clone())); }); // Test 4: Tick loop on many threads. thread::scope(|scope| { let (_signal, shutdown) = async_channel::bounded::<()>(1); for _ in 0..16 { let shutdown = shutdown.clone(); let ex = &ex; scope.spawn(move || { block_on(async move { let ticker = async { loop { ex.tick().await; } }; shutdown.recv().or(ticker).await }) }); } block_on(f(ex.clone())); }); } #[test] fn smoke() { do_run(|ex| async move { ex.spawn(async {}).await }); } #[test] fn yield_now() { do_run(|ex| async move { ex.spawn(future::yield_now()).await }) } #[test] fn timer() { do_run(|ex| async move { ex.spawn(async_io::Timer::after(Duration::from_millis(5))) .await; }) } async-executor-1.13.1/tests/local_queue.rs000066400000000000000000000013411466710771200205660ustar00rootroot00000000000000use async_executor::Executor; use futures_lite::{future, pin}; #[test] fn two_queues() { future::block_on(async { // Create an executor with two runners. let ex = Executor::new(); let (run1, run2) = ( ex.run(future::pending::<()>()), ex.run(future::pending::<()>()), ); let mut run1 = Box::pin(run1); pin!(run2); // Poll them both. assert!(future::poll_once(run1.as_mut()).await.is_none()); assert!(future::poll_once(run2.as_mut()).await.is_none()); // Drop the first one, which should leave the local queue in the `None` state. drop(run1); assert!(future::poll_once(run2.as_mut()).await.is_none()); }); } async-executor-1.13.1/tests/panic_prop.rs000066400000000000000000000006011466710771200204200ustar00rootroot00000000000000use async_executor::Executor; use futures_lite::{future, prelude::*}; #[test] fn test_panic_propagation() { let ex = Executor::new(); let task = ex.spawn(async { panic!("should be caught by the task") }); // Running the executor should not panic. assert!(ex.try_tick()); // Polling the task should. assert!(future::block_on(task.catch_unwind()).is_err()); } async-executor-1.13.1/tests/spawn_many.rs000066400000000000000000000021111466710771200204400ustar00rootroot00000000000000use async_executor::{Executor, LocalExecutor}; use futures_lite::future; #[cfg(not(miri))] const READY_COUNT: usize = 50_000; #[cfg(miri)] const READY_COUNT: usize = 505; #[test] fn spawn_many() { future::block_on(async { let ex = Executor::new(); // Spawn a lot of tasks. let mut tasks = vec![]; ex.spawn_many((0..READY_COUNT).map(future::ready), &mut tasks); // Run all of the tasks in parallel. ex.run(async move { for (i, task) in tasks.into_iter().enumerate() { assert_eq!(task.await, i); } }) .await; }); } #[test] fn spawn_many_local() { future::block_on(async { let ex = LocalExecutor::new(); // Spawn a lot of tasks. let mut tasks = vec![]; ex.spawn_many((0..READY_COUNT).map(future::ready), &mut tasks); // Run all of the tasks in parallel. ex.run(async move { for (i, task) in tasks.into_iter().enumerate() { assert_eq!(task.await, i); } }) .await; }); }