pax_global_header00006660000000000000000000000064145051770770014527gustar00rootroot0000000000000052 comment=2cfb6e4ed03c7eaf6c5fb2d3170ac870ba0a9b9d async-executor-1.5.4/000077500000000000000000000000001450517707700145075ustar00rootroot00000000000000async-executor-1.5.4/.github/000077500000000000000000000000001450517707700160475ustar00rootroot00000000000000async-executor-1.5.4/.github/dependabot.yml000066400000000000000000000002331450517707700206750ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: cargo directory: / schedule: interval: weekly commit-message: prefix: '' labels: [] async-executor-1.5.4/.github/workflows/000077500000000000000000000000001450517707700201045ustar00rootroot00000000000000async-executor-1.5.4/.github/workflows/ci.yml000066400000000000000000000046771450517707700212400ustar00rootroot00000000000000name: 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: 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 msrv: runs-on: ubuntu-latest strategy: matrix: # When updating this, the reminder to update the minimum supported # Rust version in Cargo.toml. rust: ['1.61'] steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} - run: cargo build 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 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.5.4/.github/workflows/release.yml000066400000000000000000000006411450517707700222500ustar00rootroot00000000000000name: 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.5.4/.gitignore000066400000000000000000000000231450517707700164720ustar00rootroot00000000000000/target Cargo.lock async-executor-1.5.4/CHANGELOG.md000066400000000000000000000025201450517707700163170ustar00rootroot00000000000000# 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.5.4/Cargo.toml000066400000000000000000000016121450517707700164370ustar00rootroot00000000000000[package] name = "async-executor" # When publishing a new version: # - Update CHANGELOG.md # - Create "v1.x.y" git tag version = "1.5.4" authors = ["Stjepan Glavina "] edition = "2018" rust-version = "1.61" 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 = ["/.*"] [dependencies] async-lock = "2.6" async-task = "4.0.0" concurrent-queue = "2.0.0" fastrand = "2.0.0" futures-lite = { version = "1.11.0", default-features = false } slab = "0.4.4" [dev-dependencies] async-channel = "1.4.1" async-io = "1.1.9" criterion = { version = "0.4.0", default-features = false, features = ["cargo_bench_support"] } easy-parallel = "3.1.0" once_cell = "1.16.0" [[bench]] name = "executor" harness = false async-executor-1.5.4/LICENSE-APACHE000066400000000000000000000251371450517707700164430ustar00rootroot00000000000000 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.5.4/LICENSE-MIT000066400000000000000000000017771450517707700161570ustar00rootroot00000000000000Permission 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.5.4/README.md000066400000000000000000000024171450517707700157720ustar00rootroot00000000000000# 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. ## 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.5.4/benches/000077500000000000000000000000001450517707700161165ustar00rootroot00000000000000async-executor-1.5.4/benches/executor.rs000066400000000000000000000100211450517707700203140ustar00rootroot00000000000000use std::future::Future; use std::thread::available_parallelism; use async_executor::Executor; 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(); 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 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 (group_name, multithread) in [("single_thread", false), ("multi_thread", true)].iter() { let mut group = c.benchmark_group(group_name.to_string()); group.bench_function("executor::spawn_one", |b| { run( || { b.iter(|| { future::block_on(async { EX.spawn(async {}).await }); }); }, *multithread, ); }); group.bench_function("executor::spawn_many_local", |b| { 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("executor::spawn_recursively", |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; } } } 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("executor::yield_now", |b| { 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, ); }); } } criterion_group!(benches, create, running_benches); criterion_main!(benches); async-executor-1.5.4/examples/000077500000000000000000000000001450517707700163255ustar00rootroot00000000000000async-executor-1.5.4/examples/priority.rs000066400000000000000000000042171450517707700205600ustar00rootroot00000000000000//! An executor with task priorities. use std::future::Future; 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.5.4/src/000077500000000000000000000000001450517707700152765ustar00rootroot00000000000000async-executor-1.5.4/src/lib.rs000066400000000000000000000764331450517707700164270ustar00rootroot00000000000000//! Async executors. //! //! # 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)] #![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" )] use std::cell::RefCell; use std::fmt; use std::future::Future; use std::marker::PhantomData; use std::panic::{RefUnwindSafe, UnwindSafe}; use std::rc::Rc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, RwLock, TryLockError}; use std::task::{Poll, Waker}; use async_lock::OnceCell; use async_task::Runnable; use concurrent_queue::ConcurrentQueue; use futures_lite::{future, prelude::*}; use slab::Slab; #[doc(no_inline)] pub use async_task::Task; /// 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: OnceCell>, /// Makes the `'a` lifetime invariant. _marker: PhantomData>, } unsafe impl Send for Executor<'_> {} 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: OnceCell::new(), _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(); // Remove the task from the set of active tasks when the future finishes. let index = active.vacant_entry().key(); let state = self.state().clone(); 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. let (runnable, task) = unsafe { async_task::spawn_unchecked(future, self.schedule()) }; active.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 { match self.state().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.state().notify(); // Run the task. runnable.run(); true } } } /// 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) { let state = self.state(); let runnable = Ticker::new(state).runnable().await; runnable.run(); } /// 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 { let runner = Runner::new(self.state()); let mut rng = fastrand::Rng::new(); // Set the local queue while we're running. LocalQueue::set(self.state(), &runner.local, { let runner = &runner; async move { // 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 } }) .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().clone(); // If possible, push into the current local queue and notify the ticker. move |runnable| { let mut runnable = Some(runnable); // Try to push into the local queue. LocalQueue::with(|local_queue| { // Make sure that we don't accidentally push to an executor that isn't ours. if local_queue.state != &*state as *const State as usize { return; } if let Err(e) = local_queue.queue.push(runnable.take().unwrap()) { runnable = Some(e.into_inner()); return; } local_queue.waker.wake_by_ref(); }); // If the local queue push failed, just push to the global queue. if let Some(runnable) = runnable { state.queue.push(runnable).unwrap(); state.notify(); } } } /// Returns a reference to the inner state. fn state(&self) -> &Arc { self.state.get_or_init_blocking(|| Arc::new(State::new())) } } impl Drop for Executor<'_> { fn drop(&mut self) { if let Some(state) = self.state.get() { let mut active = state.active.lock().unwrap(); 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(); // Remove the task from the set of active tasks when the future finishes. let index = active.vacant_entry().key(); let state = self.inner().state().clone(); 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. let (runnable, task) = unsafe { async_task::spawn_unchecked(future, self.schedule()) }; active.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::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 function that schedules a runnable task when it gets woken up. fn schedule(&self) -> impl Fn(Runnable) + Send + Sync + 'static { let state = self.inner().state().clone(); move |runnable| { state.queue.push(runnable).unwrap(); state.notify(); } } /// 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. 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::SeqCst, Ordering::SeqCst) .is_ok() { let waker = self.sleepers.lock().unwrap().notify(); if let Some(w) = waker { w.wake(); } } } } /// 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 { if !item.1.will_wake(waker) { item.1 = waker.clone(); } 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: AtomicUsize, } impl Ticker<'_> { /// Creates a ticker. fn new(state: &State) -> Ticker<'_> { Ticker { state, sleeping: AtomicUsize::new(0), } } /// Moves the ticker into sleeping and unnotified state. /// /// Returns `false` if the ticker was already sleeping and unnotified. fn sleep(&self, waker: &Waker) -> bool { let mut sleepers = self.state.sleepers.lock().unwrap(); match self.sleeping.load(Ordering::SeqCst) { // Move to sleeping state. 0 => self .sleeping .store(sleepers.insert(waker), Ordering::SeqCst), // Already sleeping, check if notified. id => { if !sleepers.update(id, waker) { return false; } } } self.state .notified .swap(sleepers.is_notified(), Ordering::SeqCst); true } /// Moves the ticker into woken state. fn wake(&self) { let id = self.sleeping.swap(0, Ordering::SeqCst); if id != 0 { let mut sleepers = self.state.sleepers.lock().unwrap(); sleepers.remove(id); self.state .notified .swap(sleepers.is_notified(), Ordering::SeqCst); } } /// Waits for the next runnable task to run. async fn runnable(&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(&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. let id = self.sleeping.swap(0, Ordering::SeqCst); if id != 0 { let mut sleepers = self.state.sleepers.lock().unwrap(); let notified = sleepers.remove(id); self.state .notified .swap(sleepers.is_notified(), Ordering::SeqCst); // 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: AtomicUsize, } 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: AtomicUsize::new(0), }; state .local_queues .write() .unwrap() .push(runner.local.clone()); runner } /// Waits for the next runnable task to run. async fn runnable(&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. let ticks = self.ticks.fetch_add(1, Ordering::SeqCst); if 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(); } } } /// The state of the currently running local queue. struct LocalQueue { /// The pointer to the state of the executor. /// /// Used to make sure we don't push runnables to the wrong executor. state: usize, /// The concurrent queue. queue: Arc>, /// The waker for the runnable. waker: Waker, } impl LocalQueue { /// Run a function with the current local queue. fn with(f: impl FnOnce(&LocalQueue) -> R) -> Option { std::thread_local! { /// The current local queue. static LOCAL_QUEUE: RefCell> = RefCell::new(None); } impl LocalQueue { /// Run a function with a set local queue. async fn set( state: &State, queue: &Arc>, fut: F, ) -> F::Output where F: Future, { // Make the `LocalQueue` structure. let make_local_queue = |waker: &Waker| LocalQueue { state: state as *const State as usize, queue: queue.clone(), waker: waker.clone(), }; // Store the local queue and the current waker. let mut old = with_waker(|waker| { LOCAL_QUEUE.with(move |slot| slot.borrow_mut().replace(make_local_queue(waker))) }) .await; // Restore the old local queue on drop. let _guard = CallOnDrop(move || { let old = old.take(); let _ = LOCAL_QUEUE.try_with(move |slot| { *slot.borrow_mut() = old; }); }); // Pin the future. futures_lite::pin!(fut); // Run it such that the waker is updated every time it's polled. future::poll_fn(move |cx| { LOCAL_QUEUE .try_with({ let waker = cx.waker(); move |slot| { let mut slot = slot.borrow_mut(); let qaw = match slot.as_mut() { None => { // Another local queue dropped itself and replaced with None, // we can take its place! *slot = Some(make_local_queue(waker)); return; } Some(qaw) => qaw, }; // If we've been replaced, just ignore the slot. if !Arc::ptr_eq(&qaw.queue, queue) { return; } // Update the waker, if it has changed. if !qaw.waker.will_wake(waker) { qaw.waker = waker.clone(); } } }) .ok(); // Poll the future. fut.as_mut().poll(cx) }) .await } } LOCAL_QUEUE .try_with(|local_queue| local_queue.borrow().as_ref().map(f)) .ok() .flatten() } } /// 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 state = match executor.state.get() { Some(state) => state, None => { // 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(); } }; /// 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)(); } } /// Run a closure with the current waker. fn with_waker R, R>(f: F) -> impl Future { let mut f = Some(f); future::poll_fn(move |cx| { let f = f.take().unwrap(); Poll::Ready(f(cx.waker())) }) } fn _ensure_send_and_sync() { use futures_lite::future::pending; fn is_send(_: T) {} fn is_sync(_: 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()); /// ```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.5.4/tests/000077500000000000000000000000001450517707700156515ustar00rootroot00000000000000async-executor-1.5.4/tests/different_executors.rs000066400000000000000000000020151450517707700222640ustar00rootroot00000000000000use 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.5.4/tests/drop.rs000066400000000000000000000061731450517707700171720ustar00rootroot00000000000000use 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); } #[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); } struct CallOnDrop(F); impl Drop for CallOnDrop { fn drop(&mut self) { (self.0)(); } } async-executor-1.5.4/tests/local_queue.rs000066400000000000000000000013411450517707700205140ustar00rootroot00000000000000use 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()); }); }