├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── examples ├── future.rs └── sync.rs ├── src ├── future.rs ├── lib.rs ├── no_std.rs └── sync.rs └── tests ├── future.rs └── sync.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: al8n 2 | patreon: al8n -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | # Ignore bors branches, since they are covered by `clippy_bors.yml` 6 | branches: 7 | - main 8 | # Don't run Clippy tests, when only textfiles were modified 9 | paths-ignore: 10 | - 'README' 11 | - 'COPYRIGHT' 12 | - 'LICENSE-*' 13 | - '**.md' 14 | - '**.txt' 15 | pull_request: 16 | # Don't run Clippy tests, when only textfiles were modified 17 | paths-ignore: 18 | - 'README' 19 | - 'COPYRIGHT' 20 | - 'LICENSE-*' 21 | - '**.md' 22 | - '**.txt' 23 | 24 | env: 25 | CARGO_TERM_COLOR: always 26 | 27 | jobs: 28 | # Check formatting 29 | rustfmt: 30 | name: rustfmt 31 | runs-on: ubuntu-latest 32 | steps: 33 | - uses: actions/checkout@v3 34 | - name: Install Rust 35 | run: rustup update stable && rustup default stable 36 | - name: Check formatting 37 | run: cargo fmt --all -- --check 38 | 39 | # Apply clippy lints 40 | clippy: 41 | name: clippy 42 | runs-on: ubuntu-latest 43 | steps: 44 | - uses: actions/checkout@v3 45 | - name: Apply clippy lints 46 | run: cargo clippy --all-features 47 | 48 | build: 49 | runs-on: ubuntu-latest 50 | strategy: 51 | matrix: 52 | rust: 53 | - nightly 54 | steps: 55 | - uses: actions/checkout@v2 56 | - name: Install latest nightly 57 | uses: actions-rs/toolchain@v1 58 | with: 59 | toolchain: ${{ matrix.rust }} 60 | override: true 61 | components: rustfmt, clippy 62 | 63 | - uses: actions/cache@v2 64 | with: 65 | path: | 66 | ~/.cargo/registry 67 | ~/.cargo/git 68 | target 69 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 70 | 71 | - name: Run cargo check 72 | uses: actions-rs/cargo@v1 73 | with: 74 | command: check 75 | future: 76 | name: future 77 | strategy: 78 | matrix: 79 | os: 80 | - ubuntu-latest 81 | - macos-latest 82 | - windows-latest 83 | runs-on: ${{ matrix.os }} 84 | steps: 85 | - uses: actions/checkout@v3 86 | - name: Install Rust 87 | # --no-self-update is necessary because the windows environment cannot self-update rustup.exe. 88 | run: rustup update stable --no-self-update && rustup default stable 89 | - name: Test 90 | run: cargo test --lib --features future 91 | 92 | no_std: 93 | name: no_std 94 | strategy: 95 | matrix: 96 | os: 97 | - ubuntu-latest 98 | - macos-latest 99 | - windows-latest 100 | runs-on: ${{ matrix.os }} 101 | steps: 102 | - uses: actions/checkout@v3 103 | - name: Install Rust 104 | # --no-self-update is necessary because the windows environment cannot self-update rustup.exe. 105 | run: rustup update stable --no-self-update && rustup default stable 106 | - name: Test 107 | run: cargo build --no-default-features --features alloc 108 | no_std_and_future: 109 | name: no_std & future 110 | strategy: 111 | matrix: 112 | os: 113 | - ubuntu-latest 114 | - macos-latest 115 | - windows-latest 116 | runs-on: ${{ matrix.os }} 117 | steps: 118 | - uses: actions/checkout@v3 119 | - name: Install Rust 120 | # --no-self-update is necessary because the windows environment cannot self-update rustup.exe. 121 | run: rustup update stable --no-self-update && rustup default stable 122 | - name: Test 123 | run: cargo build --no-default-features --features alloc,future 124 | sync: 125 | name: sync 126 | strategy: 127 | matrix: 128 | os: 129 | - ubuntu-latest 130 | - macos-latest 131 | - windows-latest 132 | runs-on: ${{ matrix.os }} 133 | steps: 134 | - uses: actions/checkout@v3 135 | - name: Install Rust 136 | # --no-self-update is necessary because the windows environment cannot self-update rustup.exe. 137 | run: rustup update stable --no-self-update && rustup default stable 138 | - name: Test 139 | run: cargo test --lib 140 | 141 | coverage: 142 | name: cargo tarpaulin 143 | runs-on: ubuntu-latest 144 | needs: 145 | - no_std 146 | - future 147 | - sync 148 | - build 149 | - clippy 150 | - rustfmt 151 | steps: 152 | - uses: actions/checkout@v3 153 | - name: Install latest nightly 154 | uses: actions-rs/toolchain@v1 155 | with: 156 | toolchain: nightly 157 | override: true 158 | - uses: actions-rs/install@v0.1 159 | with: 160 | crate: cargo-tarpaulin 161 | version: latest 162 | - name: Cache ~/.cargo 163 | uses: actions/cache@v3 164 | with: 165 | path: ~/.cargo 166 | key: ${{ runner.os }}-coverage-dotcargo 167 | - name: Cache cargo build 168 | uses: actions/cache@v3 169 | with: 170 | path: target 171 | key: ${{ runner.os }}-coverage-cargo-build-target 172 | - name: Run tarpaulin 173 | uses: actions-rs/cargo@v1 174 | with: 175 | command: tarpaulin 176 | args: --all-features --run-types tests --run-types doctests --workspace --out xml 177 | - name: Upload to codecov.io 178 | uses: codecov/codecov-action@v3.1.1 179 | with: 180 | token: ${{ secrets.CODECOV_TOKEN }} 181 | fail_ci_if_error: true 182 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Al Liu "] 3 | name = "wg" 4 | description = "Golang like WaitGroup implementation for sync/async Rust." 5 | homepage = "https://github.com/al8n/wg" 6 | repository = "https://github.com/al8n/wg.git" 7 | documentation = "https://docs.rs/wg/" 8 | readme = "README.md" 9 | version = "0.9.2" 10 | license = "MIT OR Apache-2.0" 11 | keywords = ["waitgroup", "async", "sync", "notify", "wake"] 12 | categories = ["asynchronous", "concurrency", "data-structures", "no-std"] 13 | edition = "2021" 14 | 15 | [features] 16 | default = ["std", "parking_lot", "triomphe"] 17 | alloc = ["crossbeam-utils"] 18 | std = ["triomphe?/default", "event-listener?/default", "futures-core?/default"] 19 | triomphe = ["dep:triomphe"] 20 | parking_lot = ["dep:parking_lot"] 21 | future = ["event-listener", "pin-project-lite"] 22 | 23 | [dependencies] 24 | parking_lot = { version = "0.12", optional = true } 25 | triomphe = { version = "0.1", optional = true, default-features = false } 26 | event-listener = { version = "5", optional = true, default-features = false, features = ["portable-atomic"] } 27 | 28 | pin-project-lite = { version = "0.2", optional = true } 29 | futures-core = { version = "^0.3.31", default-features = false, optional = true } 30 | 31 | crossbeam-utils = { version = "0.8", optional = true, default-features = false } 32 | 33 | [dev-dependencies] 34 | agnostic-lite = { version = "^0.3.16", features = ["smol", "async-std", "tokio", "time"] } 35 | tokio = { version = "1", features = ["full"] } 36 | async-std = { version = "1", features = ["attributes"] } 37 | smol = "2" 38 | 39 | [package.metadata.docs.rs] 40 | all-features = true 41 | rustdoc-args = ["--cfg", "docsrs"] 42 | 43 | [[test]] 44 | name = "future" 45 | path = "tests/future.rs" 46 | required-features = ["tokio"] 47 | 48 | [[test]] 49 | name = "sync" 50 | path = "tests/sync.rs" 51 | 52 | [[example]] 53 | name = "future" 54 | path = "examples/future.rs" 55 | required-features = ["tokio"] 56 | 57 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

wg

3 |
4 |
5 | 6 | Golang like WaitGroup implementation for sync/async Rust, support `no_std` environment. 7 | 8 | [github][Github-url] 9 | [Build][CI-url] 10 | [codecov][codecov-url] 11 | 12 | [docs.rs][doc-url] 13 | [crates.io][crates-url] 14 | [crates.io][crates-url] 15 | 16 | license 17 |
18 | 19 | ## Introduction 20 | 21 | By default, blocking version `WaitGroup` is enabled. 22 | 23 | If you are using other async runtime, you need to 24 | enbale `future` feature in your `Cargo.toml` and use `wg::AsyncWaitGroup`. 25 | 26 | 27 | ## Installation 28 | 29 | - std 30 | 31 | ```toml 32 | [dependencies] 33 | wg = "0.9" 34 | ``` 35 | 36 | 37 | - `future` 38 | 39 | ```toml 40 | [dependencies] 41 | wg = { version = "0.9", features = ["future"] } 42 | ``` 43 | 44 | - no_std 45 | 46 | ```toml 47 | [dependencies] 48 | wg = { version = "0.9", default_features = false, features = ["alloc"] } 49 | ``` 50 | 51 | - no_std & future 52 | 53 | ```toml 54 | [dependencies] 55 | wg = { version = "0.9", default_features = false, features = ["alloc", "future"] } 56 | ``` 57 | 58 | ## Examples 59 | 60 | Please see [examples](./examples) for details. 61 | 62 | ## Acknowledgements 63 | 64 | - Inspired by Golang sync.WaitGroup and [`crossbeam_utils::WaitGroup`]. 65 | 66 | ## License 67 | 68 | 69 | Licensed under either of Apache License, Version 70 | 2.0 or MIT license at your option. 71 | 72 | 73 | 74 | 75 | Unless you explicitly state otherwise, any contribution intentionally submitted 76 | for inclusion in this project by you, as defined in the Apache-2.0 license, 77 | shall be dual licensed as above, without any additional terms or conditions. 78 | 79 | 80 | [ibraheemdev's `AwaitGroup`]: https://github.com/ibraheemdev/awaitgroup 81 | [`crossbeam_utils::WaitGroup`]: https://docs.rs/crossbeam/0.8.1/crossbeam/sync/struct.WaitGroup.html 82 | [Github-url]: https://github.com/al8n/wg/ 83 | [CI-url]: https://github.com/al8n/wg/actions/workflows/ci.yml 84 | [doc-url]: https://docs.rs/wg 85 | [crates-url]: https://crates.io/crates/wg 86 | [codecov-url]: https://app.codecov.io/gh/al8n/wg/ 87 | -------------------------------------------------------------------------------- /examples/future.rs: -------------------------------------------------------------------------------- 1 | use std::sync::atomic::{AtomicUsize, Ordering}; 2 | use std::sync::Arc; 3 | use tokio::{ 4 | spawn, 5 | time::{sleep, Duration}, 6 | }; 7 | use wg::AsyncWaitGroup; 8 | 9 | #[tokio::main] 10 | async fn main() { 11 | async_std::task::block_on(async { 12 | let wg = AsyncWaitGroup::new(); 13 | let ctr = Arc::new(AtomicUsize::new(0)); 14 | 15 | for _ in 0..5 { 16 | let ctrx = ctr.clone(); 17 | let t_wg = wg.add(1); 18 | spawn(async move { 19 | // mock some time consuming task 20 | sleep(Duration::from_millis(50)).await; 21 | ctrx.fetch_add(1, Ordering::Relaxed); 22 | 23 | // mock task is finished 24 | t_wg.done(); 25 | }); 26 | } 27 | 28 | wg.wait().await; 29 | assert_eq!(ctr.load(Ordering::Relaxed), 5); 30 | }); 31 | } 32 | -------------------------------------------------------------------------------- /examples/sync.rs: -------------------------------------------------------------------------------- 1 | use std::sync::atomic::{AtomicUsize, Ordering}; 2 | use std::sync::Arc; 3 | use std::thread::{sleep, spawn}; 4 | use std::time::Duration; 5 | use wg::WaitGroup; 6 | 7 | fn main() { 8 | let wg = WaitGroup::new(); 9 | let ctr = Arc::new(AtomicUsize::new(0)); 10 | 11 | for _ in 0..5 { 12 | let ctrx = ctr.clone(); 13 | let t_wg = wg.add(1); 14 | spawn(move || { 15 | // mock some time consuming task 16 | sleep(Duration::from_millis(50)); 17 | ctrx.fetch_add(1, Ordering::Relaxed); 18 | 19 | // mock task is finished 20 | t_wg.done(); 21 | }); 22 | } 23 | 24 | wg.wait(); 25 | assert_eq!(ctr.load(Ordering::Relaxed), 5); 26 | } 27 | -------------------------------------------------------------------------------- /src/future.rs: -------------------------------------------------------------------------------- 1 | use event_listener::{Event, EventListener}; 2 | 3 | use core::{ 4 | pin::Pin, 5 | sync::atomic::{AtomicUsize, Ordering}, 6 | task::{Context, Poll}, 7 | }; 8 | 9 | #[cfg(feature = "triomphe")] 10 | use triomphe::Arc; 11 | 12 | #[cfg(all(feature = "std", not(feature = "triomphe")))] 13 | use std::sync::Arc; 14 | 15 | #[cfg(all(not(feature = "std"), not(feature = "triomphe")))] 16 | use alloc::sync::Arc; 17 | 18 | #[derive(Debug)] 19 | struct AsyncInner { 20 | counter: AtomicUsize, 21 | event: Event, 22 | } 23 | 24 | /// An AsyncWaitGroup waits for a collection of threads to finish. 25 | /// 26 | /// The main thread calls [`add`] to set the number of 27 | /// thread to wait for. Then each of the tasks 28 | /// runs and calls Done when finished. At the same time, 29 | /// Wait can be used to block until all tasks have finished. 30 | /// 31 | /// # Example 32 | /// 33 | /// ```rust 34 | /// use wg::AsyncWaitGroup; 35 | /// use std::sync::Arc; 36 | /// use std::sync::atomic::{AtomicUsize, Ordering}; 37 | /// use std::time::Duration; 38 | /// use async_std::task::{spawn, sleep}; 39 | /// 40 | /// # async_std::task::block_on(async { 41 | /// let wg = AsyncWaitGroup::new(); 42 | /// let ctr = Arc::new(AtomicUsize::new(0)); 43 | /// 44 | /// for _ in 0..5 { 45 | /// let ctrx = ctr.clone(); 46 | /// let t_wg = wg.add(1); 47 | /// spawn(async move { 48 | /// // mock some time consuming task 49 | /// sleep(Duration::from_millis(50)).await; 50 | /// ctrx.fetch_add(1, Ordering::Relaxed); 51 | /// 52 | /// // mock task is finished 53 | /// t_wg.done(); 54 | /// }); 55 | /// } 56 | /// 57 | /// wg.wait().await; 58 | /// assert_eq!(ctr.load(Ordering::Relaxed), 5); 59 | /// # }) 60 | /// ``` 61 | /// 62 | /// [`wait`]: struct.AsyncWaitGroup.html#method.wait 63 | /// [`add`]: struct.AsyncWaitGroup.html#method.add 64 | #[cfg_attr(docsrs, doc(cfg(feature = "future")))] 65 | pub struct AsyncWaitGroup { 66 | inner: Arc, 67 | } 68 | 69 | impl Default for AsyncWaitGroup { 70 | fn default() -> Self { 71 | Self { 72 | inner: Arc::new(AsyncInner { 73 | counter: AtomicUsize::new(0), 74 | event: Event::new(), 75 | }), 76 | } 77 | } 78 | } 79 | 80 | impl From for AsyncWaitGroup { 81 | fn from(count: usize) -> Self { 82 | Self { 83 | inner: Arc::new(AsyncInner { 84 | counter: AtomicUsize::new(count), 85 | event: Event::new(), 86 | }), 87 | } 88 | } 89 | } 90 | 91 | impl Clone for AsyncWaitGroup { 92 | fn clone(&self) -> Self { 93 | Self { 94 | inner: self.inner.clone(), 95 | } 96 | } 97 | } 98 | 99 | impl core::fmt::Debug for AsyncWaitGroup { 100 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 101 | f.debug_struct("AsyncWaitGroup") 102 | .field("counter", &self.inner.counter) 103 | .finish() 104 | } 105 | } 106 | 107 | impl AsyncWaitGroup { 108 | /// Creates a new `AsyncWaitGroup` 109 | pub fn new() -> Self { 110 | Self::default() 111 | } 112 | 113 | /// Adds delta to the WaitGroup counter. 114 | /// If the counter becomes zero, all threads blocked on [`wait`] are released. 115 | /// 116 | /// Note that calls with a delta that occur when the counter is zero 117 | /// must happen before a Wait. 118 | /// Typically this means the calls to add should execute before the statement 119 | /// creating the thread or other event to be waited for. 120 | /// If a `AsyncWaitGroup` is reused to [`wait`] for several independent sets of events, 121 | /// new `add` calls must happen after all previous [`wait`] calls have returned. 122 | /// 123 | /// # Example 124 | /// 125 | /// ```rust 126 | /// use wg::AsyncWaitGroup; 127 | /// use async_std::task::spawn; 128 | /// 129 | /// # async_std::task::block_on(async { 130 | /// let wg = AsyncWaitGroup::new(); 131 | /// 132 | /// wg.add(3); 133 | /// (0..3).for_each(|_| { 134 | /// let t_wg = wg.clone(); 135 | /// spawn(async move { 136 | /// // do some time consuming work 137 | /// t_wg.done(); 138 | /// }); 139 | /// }); 140 | /// 141 | /// wg.wait().await; 142 | /// # }) 143 | /// ``` 144 | /// 145 | /// [`wait`]: struct.AsyncWaitGroup.html#method.wait 146 | pub fn add(&self, num: usize) -> Self { 147 | self.inner.counter.fetch_add(num, Ordering::AcqRel); 148 | 149 | Self { 150 | inner: self.inner.clone(), 151 | } 152 | } 153 | 154 | /// Decrements the AsyncWaitGroup counter by one, returning the remaining count. 155 | /// 156 | /// # Example 157 | /// 158 | /// ```rust 159 | /// use wg::AsyncWaitGroup; 160 | /// use async_std::task::spawn; 161 | /// 162 | /// # async_std::task::block_on(async { 163 | /// let wg = AsyncWaitGroup::new(); 164 | /// wg.add(1); 165 | /// let t_wg = wg.clone(); 166 | /// spawn(async move { 167 | /// // do some time consuming task 168 | /// t_wg.done(); 169 | /// }); 170 | /// # }) 171 | /// ``` 172 | pub fn done(&self) -> usize { 173 | match self 174 | .inner 175 | .counter 176 | .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| { 177 | if v != 0 { 178 | Some(v - 1) 179 | } else { 180 | None 181 | } 182 | }) { 183 | Ok(x) => { 184 | self.inner.event.notify(usize::MAX); 185 | x 186 | } 187 | Err(x) => { 188 | assert_eq!(x, 0); 189 | x 190 | } 191 | } 192 | } 193 | 194 | /// waitings return how many jobs are waiting. 195 | pub fn waitings(&self) -> usize { 196 | self.inner.counter.load(Ordering::Acquire) 197 | } 198 | 199 | /// wait blocks until the [`AsyncWaitGroup`] counter is zero. 200 | /// 201 | /// # Example 202 | /// 203 | /// ```rust 204 | /// use wg::AsyncWaitGroup; 205 | /// use async_std::task::spawn; 206 | /// 207 | /// # async_std::task::block_on(async { 208 | /// let wg = AsyncWaitGroup::new(); 209 | /// wg.add(1); 210 | /// let t_wg = wg.clone(); 211 | /// 212 | /// spawn(async move { 213 | /// // do some time consuming task 214 | /// t_wg.done() 215 | /// }); 216 | /// 217 | /// // wait other thread completes 218 | /// wg.wait().await; 219 | /// # }) 220 | /// ``` 221 | pub fn wait(&self) -> WaitGroupFuture<'_> { 222 | WaitGroupFuture { 223 | inner: self, 224 | notified: self.inner.event.listen(), 225 | _pin: core::marker::PhantomPinned, 226 | } 227 | } 228 | 229 | /// Wait blocks until the [`AsyncWaitGroup`] counter is zero. This method is 230 | /// intended to be used in a non-async context, 231 | /// e.g. when implementing the [`Drop`] trait. 232 | /// 233 | /// The implementation is like a spin lock, which is not efficient, so use it with caution. 234 | /// 235 | /// # Example 236 | /// 237 | /// ```rust 238 | /// use wg::AsyncWaitGroup; 239 | /// use async_std::task::spawn; 240 | /// 241 | /// # async_std::task::block_on(async { 242 | /// let wg = AsyncWaitGroup::new(); 243 | /// wg.add(1); 244 | /// let t_wg = wg.clone(); 245 | /// 246 | /// spawn(async move { 247 | /// // do some time consuming task 248 | /// t_wg.done() 249 | /// }); 250 | /// 251 | /// // wait other thread completes 252 | /// wg.wait_blocking(); 253 | /// # }) 254 | /// ``` 255 | #[cfg(feature = "std")] 256 | #[cfg_attr(docsrs, doc(cfg(feature = "std")))] 257 | pub fn wait_blocking(&self) { 258 | use event_listener::Listener; 259 | 260 | while self.inner.counter.load(Ordering::SeqCst) != 0 { 261 | let ln = self.inner.event.listen(); 262 | // Check the flag again after creating the listener. 263 | if self.inner.counter.load(Ordering::SeqCst) == 0 { 264 | return; 265 | } 266 | ln.wait(); 267 | } 268 | } 269 | } 270 | 271 | pin_project_lite::pin_project! { 272 | /// A future returned by [`AsyncWaitGroup::wait()`]. 273 | #[derive(Debug)] 274 | #[must_use = "futures do nothing unless you `.await` or poll them"] 275 | pub struct WaitGroupFuture<'a> { 276 | inner: &'a AsyncWaitGroup, 277 | #[pin] 278 | notified: EventListener, 279 | #[pin] 280 | _pin: core::marker::PhantomPinned, 281 | } 282 | } 283 | 284 | impl core::future::Future for WaitGroupFuture<'_> { 285 | type Output = (); 286 | 287 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 288 | if self.inner.inner.counter.load(Ordering::SeqCst) == 0 { 289 | return Poll::Ready(()); 290 | } 291 | 292 | let mut this = self.project(); 293 | match this.notified.as_mut().poll(cx) { 294 | Poll::Pending => { 295 | if this.inner.inner.counter.load(Ordering::SeqCst) == 0 { 296 | Poll::Ready(()) 297 | } else { 298 | cx.waker().wake_by_ref(); 299 | Poll::Pending 300 | } 301 | } 302 | Poll::Ready(_) => { 303 | if this.inner.inner.counter.load(Ordering::SeqCst) == 0 { 304 | Poll::Ready(()) 305 | } else { 306 | *this.notified = this.inner.inner.event.listen(); 307 | cx.waker().wake_by_ref(); 308 | Poll::Pending 309 | } 310 | } 311 | } 312 | } 313 | } 314 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Al Liu (https://github.com/al8n). Licensed under MIT OR Apache-2.0. 3 | * 4 | * 5 | * 6 | * Copyright 2021 AwaitGroup authors (https://github.com/ibraheemdev/awaitgroup). Licensed under MIT. 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | #![doc = include_str!("../README.md")] 21 | #![cfg_attr(not(all(feature = "std", test)), no_std)] 22 | #![deny(missing_docs, warnings)] 23 | #![cfg_attr(docsrs, feature(doc_cfg))] 24 | #![cfg_attr(docsrs, allow(unused_attributes))] 25 | 26 | #[cfg(not(any(feature = "alloc", feature = "std")))] 27 | compile_error!("This crate can only be used when feature `alloc` or `std` is enabled"); 28 | 29 | #[cfg(not(feature = "std"))] 30 | extern crate alloc; 31 | 32 | #[cfg(feature = "std")] 33 | extern crate std; 34 | 35 | #[cfg(feature = "future")] 36 | mod future; 37 | 38 | #[cfg(feature = "future")] 39 | #[cfg_attr(docsrs, doc(cfg(feature = "future")))] 40 | pub use future::*; 41 | 42 | #[cfg(feature = "std")] 43 | mod sync; 44 | #[cfg(feature = "std")] 45 | pub use sync::*; 46 | 47 | #[cfg(not(feature = "std"))] 48 | mod no_std; 49 | #[cfg(not(feature = "std"))] 50 | pub use no_std::*; 51 | -------------------------------------------------------------------------------- /src/no_std.rs: -------------------------------------------------------------------------------- 1 | use core::sync::atomic::{AtomicUsize, Ordering}; 2 | 3 | use alloc::sync::Arc; 4 | 5 | #[derive(Debug)] 6 | struct Inner { 7 | counter: AtomicUsize, 8 | } 9 | 10 | /// An WaitGroup waits for a collection of threads to finish. 11 | /// The main thread calls [`add`] to set the number of 12 | /// thread to wait for. Then each of the tasks 13 | /// runs and calls [`WaitGroup::done`](WaitGroup::done) when finished. At the same time, 14 | /// Wait can be used to block until all tasks have finished. 15 | /// 16 | /// [`wait`]: struct.WaitGroup.html#method.wait 17 | /// [`add`]: struct.WaitGroup.html#method.add 18 | #[cfg_attr(docsrs, doc(cfg(feature = "future")))] 19 | pub struct WaitGroup { 20 | inner: Arc, 21 | } 22 | 23 | impl Default for WaitGroup { 24 | fn default() -> Self { 25 | Self { 26 | inner: Arc::new(Inner { 27 | counter: AtomicUsize::new(0), 28 | }), 29 | } 30 | } 31 | } 32 | 33 | impl From for WaitGroup { 34 | fn from(count: usize) -> Self { 35 | Self { 36 | inner: Arc::new(Inner { 37 | counter: AtomicUsize::new(count), 38 | }), 39 | } 40 | } 41 | } 42 | 43 | impl Clone for WaitGroup { 44 | fn clone(&self) -> Self { 45 | Self { 46 | inner: self.inner.clone(), 47 | } 48 | } 49 | } 50 | 51 | impl core::fmt::Debug for WaitGroup { 52 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 53 | f.debug_struct("WaitGroup") 54 | .field("counter", &self.inner.counter) 55 | .finish() 56 | } 57 | } 58 | 59 | impl WaitGroup { 60 | /// Creates a new `WaitGroup` 61 | pub fn new() -> Self { 62 | Self::default() 63 | } 64 | 65 | /// Adds delta to the WaitGroup counter. 66 | /// If the counter becomes zero, all threads blocked on [`wait`] are released. 67 | /// 68 | /// Note that calls with a delta that occur when the counter is zero 69 | /// must happen before a Wait. 70 | /// Typically this means the calls to add should execute before the statement 71 | /// creating the thread or other event to be waited for. 72 | /// If a `WaitGroup` is reused to [`wait`] for several independent sets of events, 73 | /// new `add` calls must happen after all previous [`wait`] calls have returned. 74 | /// 75 | /// # Example 76 | /// 77 | /// ```rust,ignore 78 | /// use wg::WaitGroup; 79 | /// 80 | /// let wg = WaitGroup::new(); 81 | /// 82 | /// wg.add(3); 83 | /// (0..3).for_each(|_| { 84 | /// let t_wg = wg.clone(); 85 | /// spawn(move || { 86 | /// // do some time consuming work 87 | /// t_wg.done(); 88 | /// }); 89 | /// }); 90 | /// 91 | /// wg.wait(); 92 | /// ``` 93 | /// 94 | /// [`wait`]: struct.WaitGroup.html#method.wait 95 | pub fn add(&self, num: usize) -> Self { 96 | self.inner.counter.fetch_add(num, Ordering::AcqRel); 97 | 98 | Self { 99 | inner: self.inner.clone(), 100 | } 101 | } 102 | 103 | /// Decrements the WaitGroup counter by one, returning the remaining count. 104 | /// 105 | /// # Example 106 | /// 107 | /// ```rust,ignore 108 | /// use wg::WaitGroup; 109 | /// 110 | /// let wg = WaitGroup::new(); 111 | /// wg.add(1); 112 | /// let t_wg = wg.clone(); 113 | /// spawn(move || { 114 | /// // do some time consuming task 115 | /// t_wg.done(); 116 | /// }); 117 | /// ``` 118 | pub fn done(&self) -> usize { 119 | match self 120 | .inner 121 | .counter 122 | .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| { 123 | if v != 0 { 124 | Some(v - 1) 125 | } else { 126 | None 127 | } 128 | }) { 129 | Ok(x) => x, 130 | Err(x) => { 131 | assert_eq!(x, 0); 132 | x 133 | } 134 | } 135 | } 136 | 137 | /// waitings return how many jobs are waiting. 138 | pub fn waitings(&self) -> usize { 139 | self.inner.counter.load(Ordering::Acquire) 140 | } 141 | 142 | /// wait blocks until the [`WaitGroup`] counter is zero. 143 | /// 144 | /// # Example 145 | /// 146 | /// ```rust 147 | /// use wg::WaitGroup; 148 | /// 149 | /// let wg = WaitGroup::new(); 150 | /// wg.add(1); 151 | /// let t_wg = wg.clone(); 152 | /// 153 | /// spawn(async move { 154 | /// // do some time consuming task 155 | /// t_wg.done() 156 | /// }); 157 | /// 158 | /// // wait other thread completes 159 | /// wg.wait(); 160 | /// ``` 161 | pub fn wait(&self) { 162 | while self.inner.counter.load(Ordering::SeqCst) != 0 { 163 | crossbeam_utils::Backoff::new().spin(); 164 | } 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /src/sync.rs: -------------------------------------------------------------------------------- 1 | trait Mu { 2 | type Guard<'a> 3 | where 4 | Self: 'a; 5 | fn lock_me(&self) -> Self::Guard<'_>; 6 | } 7 | 8 | #[cfg(feature = "parking_lot")] 9 | impl Mu for parking_lot::Mutex { 10 | type Guard<'a> 11 | = parking_lot::MutexGuard<'a, T> 12 | where 13 | Self: 'a; 14 | 15 | fn lock_me(&self) -> Self::Guard<'_> { 16 | self.lock() 17 | } 18 | } 19 | 20 | #[cfg(not(feature = "parking_lot"))] 21 | impl Mu for std::sync::Mutex { 22 | type Guard<'a> 23 | = std::sync::MutexGuard<'a, T> 24 | where 25 | Self: 'a; 26 | 27 | fn lock_me(&self) -> Self::Guard<'_> { 28 | self.lock().unwrap() 29 | } 30 | } 31 | 32 | #[cfg(feature = "parking_lot")] 33 | use parking_lot::{Condvar, Mutex}; 34 | #[cfg(not(feature = "triomphe"))] 35 | use std::sync::Arc; 36 | #[cfg(not(feature = "parking_lot"))] 37 | use std::sync::{Condvar, Mutex}; 38 | #[cfg(feature = "triomphe")] 39 | use triomphe::Arc; 40 | 41 | struct Inner { 42 | cvar: Condvar, 43 | count: Mutex, 44 | } 45 | 46 | /// A WaitGroup waits for a collection of threads to finish. 47 | /// 48 | /// The main thread calls [`add`] to set the number of 49 | /// thread to wait for. Then each of the goroutines 50 | /// runs and calls Done when finished. At the same time, 51 | /// Wait can be used to block until all goroutines have finished. 52 | /// 53 | /// A WaitGroup must not be copied after first use. 54 | /// 55 | /// # Example 56 | /// 57 | /// ```rust 58 | /// use wg::WaitGroup; 59 | /// use std::sync::Arc; 60 | /// use std::sync::atomic::{AtomicUsize, Ordering}; 61 | /// use std::time::Duration; 62 | /// use std::thread::{spawn, sleep}; 63 | /// 64 | /// let wg = WaitGroup::new(); 65 | /// let ctr = Arc::new(AtomicUsize::new(0)); 66 | /// 67 | /// for _ in 0..5 { 68 | /// let ctrx = ctr.clone(); 69 | /// let t_wg = wg.add(1); 70 | /// spawn(move || { 71 | /// // mock some time consuming task 72 | /// sleep(Duration::from_millis(50)); 73 | /// ctrx.fetch_add(1, Ordering::Relaxed); 74 | /// 75 | /// // mock task is finished 76 | /// t_wg.done(); 77 | /// }); 78 | /// } 79 | /// 80 | /// wg.wait(); 81 | /// assert_eq!(ctr.load(Ordering::Relaxed), 5); 82 | /// ``` 83 | /// 84 | /// [`wait`]: struct.WaitGroup.html#method.wait 85 | /// [`add`]: struct.WaitGroup.html#method.add 86 | pub struct WaitGroup { 87 | inner: Arc, 88 | } 89 | 90 | impl Default for WaitGroup { 91 | fn default() -> Self { 92 | Self { 93 | inner: Arc::new(Inner { 94 | cvar: Condvar::new(), 95 | count: Mutex::new(0), 96 | }), 97 | } 98 | } 99 | } 100 | 101 | impl From for WaitGroup { 102 | fn from(count: usize) -> Self { 103 | Self { 104 | inner: Arc::new(Inner { 105 | cvar: Condvar::new(), 106 | count: Mutex::new(count), 107 | }), 108 | } 109 | } 110 | } 111 | 112 | impl Clone for WaitGroup { 113 | fn clone(&self) -> Self { 114 | Self { 115 | inner: self.inner.clone(), 116 | } 117 | } 118 | } 119 | 120 | impl std::fmt::Debug for WaitGroup { 121 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 122 | let count = self.inner.count.lock_me(); 123 | f.debug_struct("WaitGroup").field("count", &*count).finish() 124 | } 125 | } 126 | 127 | impl WaitGroup { 128 | /// Creates a new wait group and returns the single reference to it. 129 | /// 130 | /// # Examples 131 | /// 132 | /// ``` 133 | /// use wg::WaitGroup; 134 | /// 135 | /// let wg = WaitGroup::new(); 136 | /// ``` 137 | pub fn new() -> Self { 138 | Self::default() 139 | } 140 | 141 | /// Adds delta to the WaitGroup counter. 142 | /// If the counter becomes zero, all threads blocked on [`wait`] are released. 143 | /// 144 | /// Note that calls with a delta that occur when the counter is zero 145 | /// must happen before a Wait. 146 | /// Typically this means the calls to add should execute before the statement 147 | /// creating the thread or other event to be waited for. 148 | /// If a `WaitGroup` is reused to [`wait`] for several independent sets of events, 149 | /// new `add` calls must happen after all previous [`wait`] calls have returned. 150 | /// 151 | /// # Example 152 | /// ```rust 153 | /// use wg::WaitGroup; 154 | /// 155 | /// let wg = WaitGroup::new(); 156 | /// 157 | /// wg.add(3); 158 | /// (0..3).for_each(|_| { 159 | /// let t_wg = wg.clone(); 160 | /// std::thread::spawn(move || { 161 | /// // do some time consuming work 162 | /// t_wg.done(); 163 | /// }); 164 | /// }); 165 | /// 166 | /// wg.wait(); 167 | /// ``` 168 | /// 169 | /// [`wait`]: struct.AsyncWaitGroup.html#method.wait 170 | pub fn add(&self, num: usize) -> Self { 171 | let mut ctr = self.inner.count.lock_me(); 172 | *ctr += num; 173 | Self { 174 | inner: self.inner.clone(), 175 | } 176 | } 177 | 178 | /// Decrements the WaitGroup counter by one, returning the remaining count. 179 | /// 180 | /// # Example 181 | /// 182 | /// ```rust 183 | /// use wg::WaitGroup; 184 | /// use std::thread; 185 | /// 186 | /// let wg = WaitGroup::new(); 187 | /// wg.add(1); 188 | /// let t_wg = wg.clone(); 189 | /// thread::spawn(move || { 190 | /// // do some time consuming task 191 | /// t_wg.done() 192 | /// }); 193 | /// 194 | /// ``` 195 | pub fn done(&self) -> usize { 196 | let mut val = self.inner.count.lock_me(); 197 | 198 | *val = if val.eq(&1) { 199 | self.inner.cvar.notify_all(); 200 | 0 201 | } else if val.eq(&0) { 202 | 0 203 | } else { 204 | *val - 1 205 | }; 206 | *val 207 | } 208 | 209 | /// waitings return how many jobs are waiting. 210 | pub fn waitings(&self) -> usize { 211 | *self.inner.count.lock_me() 212 | } 213 | 214 | /// wait blocks until the WaitGroup counter is zero. 215 | /// 216 | /// # Example 217 | /// 218 | /// ```rust 219 | /// use wg::WaitGroup; 220 | /// use std::thread; 221 | /// 222 | /// let wg = WaitGroup::new(); 223 | /// wg.add(1); 224 | /// let t_wg = wg.clone(); 225 | /// thread::spawn(move || { 226 | /// // do some time consuming task 227 | /// t_wg.done() 228 | /// }); 229 | /// 230 | /// // wait other thread completes 231 | /// wg.wait(); 232 | /// ``` 233 | pub fn wait(&self) { 234 | let mut ctr = self.inner.count.lock_me(); 235 | 236 | if ctr.eq(&0) { 237 | return; 238 | } 239 | 240 | while *ctr > 0 { 241 | #[cfg(feature = "parking_lot")] 242 | { 243 | self.inner.cvar.wait(&mut ctr); 244 | } 245 | 246 | #[cfg(not(feature = "parking_lot"))] 247 | { 248 | ctr = self.inner.cvar.wait(ctr).unwrap(); 249 | } 250 | } 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /tests/future.rs: -------------------------------------------------------------------------------- 1 | use agnostic_lite::{AsyncSpawner, RuntimeLite}; 2 | use wg::AsyncWaitGroup; 3 | 4 | use std::{ 5 | sync::{ 6 | atomic::{AtomicUsize, Ordering}, 7 | Arc, 8 | }, 9 | time::Duration, 10 | }; 11 | 12 | async fn basic_in() { 13 | let wg = AsyncWaitGroup::new(); 14 | let ctr = Arc::new(AtomicUsize::new(0)); 15 | 16 | for _ in 0..5 { 17 | let ctrx = ctr.clone(); 18 | let wg = wg.add(1); 19 | 20 | S::spawn_detach(async move { 21 | S::sleep(Duration::from_millis(50)).await; 22 | ctrx.fetch_add(1, Ordering::Relaxed); 23 | let remaining = wg.done(); 24 | println!("remaining: {}", remaining); 25 | }); 26 | } 27 | wg.wait().await; 28 | assert_eq!(ctr.load(Ordering::Relaxed), 5); 29 | } 30 | 31 | #[tokio::test] 32 | async fn tokio_basic() { 33 | basic_in::().await; 34 | } 35 | 36 | #[async_std::test] 37 | async fn async_std_basic() { 38 | basic_in::().await; 39 | } 40 | 41 | #[test] 42 | fn smol_basic() { 43 | smol::block_on(basic_in::()) 44 | } 45 | 46 | async fn reuse_in() { 47 | let wg = AsyncWaitGroup::new(); 48 | let ctr = Arc::new(AtomicUsize::new(0)); 49 | for _ in 0..6 { 50 | let wg = wg.add(1); 51 | let ctrx = ctr.clone(); 52 | S::spawn_detach(async move { 53 | S::sleep(Duration::from_millis(5)).await; 54 | ctrx.fetch_add(1, Ordering::Relaxed); 55 | wg.done(); 56 | }); 57 | } 58 | 59 | wg.wait().await; 60 | assert_eq!(ctr.load(Ordering::Relaxed), 6); 61 | 62 | let worker = wg.add(1); 63 | 64 | let ctrx = ctr.clone(); 65 | S::spawn_detach(async move { 66 | S::sleep(Duration::from_millis(5)).await; 67 | ctrx.fetch_add(1, Ordering::Relaxed); 68 | worker.done(); 69 | }); 70 | 71 | wg.wait().await; 72 | assert_eq!(ctr.load(Ordering::Relaxed), 7); 73 | } 74 | 75 | #[tokio::test] 76 | async fn tokio_reuse() { 77 | reuse_in::().await; 78 | } 79 | 80 | #[async_std::test] 81 | async fn async_std_reuse() { 82 | reuse_in::().await; 83 | } 84 | 85 | #[test] 86 | fn smol_reuse() { 87 | smol::block_on(reuse_in::()) 88 | } 89 | 90 | async fn nested_in() { 91 | let wg = AsyncWaitGroup::new(); 92 | let ctr = Arc::new(AtomicUsize::new(0)); 93 | for _ in 0..5 { 94 | let worker = wg.add(1); 95 | let ctrx = ctr.clone(); 96 | S::spawn_detach(async move { 97 | let nested_worker = worker.add(1); 98 | let ctrxx = ctrx.clone(); 99 | S::spawn_detach(async move { 100 | ctrxx.fetch_add(1, Ordering::Relaxed); 101 | nested_worker.done(); 102 | }); 103 | ctrx.fetch_add(1, Ordering::Relaxed); 104 | worker.done(); 105 | }); 106 | } 107 | 108 | wg.wait().await; 109 | assert_eq!(ctr.load(Ordering::Relaxed), 10); 110 | } 111 | 112 | #[tokio::test] 113 | async fn tokio_nested() { 114 | nested_in::().await; 115 | } 116 | 117 | #[async_std::test] 118 | async fn async_std_nested() { 119 | nested_in::().await; 120 | } 121 | 122 | #[test] 123 | fn smol_nested() { 124 | smol::block_on(nested_in::()) 125 | } 126 | 127 | async fn from_in() { 128 | let wg = AsyncWaitGroup::from(5); 129 | for _ in 0..5 { 130 | let t = wg.clone(); 131 | S::spawn_detach(async move { 132 | t.done(); 133 | }); 134 | } 135 | wg.wait().await; 136 | } 137 | 138 | #[async_std::test] 139 | async fn from_async_std() { 140 | from_in::().await; 141 | } 142 | 143 | #[tokio::test] 144 | async fn from_tokio() { 145 | from_in::().await; 146 | } 147 | 148 | #[test] 149 | fn from_smol() { 150 | smol::block_on(from_in::()) 151 | } 152 | 153 | #[test] 154 | fn test_async_waitings() { 155 | let wg = AsyncWaitGroup::new(); 156 | wg.add(1); 157 | wg.add(1); 158 | assert_eq!(wg.waitings(), 2); 159 | } 160 | 161 | async fn block_wait_in() { 162 | let wg = AsyncWaitGroup::new(); 163 | let t_wg = wg.add(1); 164 | S::spawn_detach(async move { 165 | // do some time consuming task 166 | t_wg.done(); 167 | S::yield_now().await; 168 | }); 169 | 170 | // wait other thread completes 171 | wg.wait_blocking(); 172 | 173 | assert_eq!(wg.waitings(), 0); 174 | } 175 | 176 | #[async_std::test] 177 | async fn block_wait_async_std() { 178 | block_wait_in::().await; 179 | } 180 | 181 | #[tokio::test(flavor = "multi_thread")] 182 | async fn block_wait_tokio() { 183 | block_wait_in::().await; 184 | } 185 | 186 | #[test] 187 | fn block_wait_smol() { 188 | smol::block_on(block_wait_in::()) 189 | } 190 | 191 | async fn wake_after_updating_in() { 192 | let wg = AsyncWaitGroup::new(); 193 | for _ in 0..100000 { 194 | let worker = wg.add(1); 195 | S::spawn_detach(async move { 196 | S::sleep(std::time::Duration::from_millis(10)).await; 197 | let mut a = 0; 198 | for _ in 0..1000 { 199 | a += 1; 200 | } 201 | println!("{}", a); 202 | S::sleep(std::time::Duration::from_millis(10)).await; 203 | worker.done(); 204 | }); 205 | } 206 | wg.wait().await; 207 | } 208 | 209 | #[async_std::test] 210 | async fn wake_after_updating_async_std() { 211 | wake_after_updating_in::().await; 212 | } 213 | 214 | #[tokio::test] 215 | async fn wake_after_updating_tokio() { 216 | wake_after_updating_in::().await; 217 | } 218 | 219 | #[test] 220 | fn wake_after_updating_smol() { 221 | smol::block_on(wake_after_updating_in::()) 222 | } 223 | 224 | #[test] 225 | fn test_clone_and_fmt() { 226 | let awg = AsyncWaitGroup::new(); 227 | let awg1 = awg.clone(); 228 | awg1.add(3); 229 | assert_eq!(format!("{:?}", awg), format!("{:?}", awg1)); 230 | } 231 | 232 | #[test] 233 | fn test_over_done() { 234 | let wg = AsyncWaitGroup::new(); 235 | assert_eq!(wg.done(), 0); 236 | assert_eq!(wg.done(), 0); 237 | assert_eq!(wg.waitings(), 0); 238 | } 239 | -------------------------------------------------------------------------------- /tests/sync.rs: -------------------------------------------------------------------------------- 1 | use std::sync::atomic::{AtomicUsize, Ordering}; 2 | use std::sync::Arc; 3 | use std::time::Duration; 4 | use wg::WaitGroup; 5 | 6 | #[test] 7 | fn test_sync_wait_group_reuse() { 8 | let wg = WaitGroup::new(); 9 | let ctr = Arc::new(AtomicUsize::new(0)); 10 | for _ in 0..6 { 11 | let wg = wg.add(1); 12 | let ctrx = ctr.clone(); 13 | std::thread::spawn(move || { 14 | std::thread::sleep(Duration::from_millis(5)); 15 | ctrx.fetch_add(1, Ordering::Relaxed); 16 | wg.done(); 17 | }); 18 | } 19 | 20 | wg.wait(); 21 | assert_eq!(ctr.load(Ordering::Relaxed), 6); 22 | 23 | let worker = wg.add(1); 24 | let ctrx = ctr.clone(); 25 | std::thread::spawn(move || { 26 | std::thread::sleep(Duration::from_millis(5)); 27 | ctrx.fetch_add(1, Ordering::Relaxed); 28 | worker.done(); 29 | }); 30 | wg.wait(); 31 | assert_eq!(ctr.load(Ordering::Relaxed), 7); 32 | } 33 | 34 | #[test] 35 | fn test_sync_wait_group_nested() { 36 | let wg = WaitGroup::new(); 37 | let ctr = Arc::new(AtomicUsize::new(0)); 38 | for _ in 0..5 { 39 | let worker = wg.add(1); 40 | let ctrx = ctr.clone(); 41 | std::thread::spawn(move || { 42 | let nested_worker = worker.add(1); 43 | let ctrxx = ctrx.clone(); 44 | std::thread::spawn(move || { 45 | ctrxx.fetch_add(1, Ordering::Relaxed); 46 | nested_worker.done(); 47 | }); 48 | ctrx.fetch_add(1, Ordering::Relaxed); 49 | worker.done(); 50 | }); 51 | } 52 | 53 | wg.wait(); 54 | assert_eq!(ctr.load(Ordering::Relaxed), 10); 55 | } 56 | 57 | #[test] 58 | fn test_sync_wait_group_from() { 59 | std::thread::scope(|s| { 60 | let wg = WaitGroup::from(5); 61 | for _ in 0..5 { 62 | let t = wg.clone(); 63 | s.spawn(move || { 64 | t.done(); 65 | }); 66 | } 67 | wg.wait(); 68 | }); 69 | } 70 | 71 | #[test] 72 | fn test_clone_and_fmt() { 73 | let swg = WaitGroup::new(); 74 | let swg1 = swg.clone(); 75 | swg1.add(3); 76 | assert_eq!(format!("{:?}", swg), format!("{:?}", swg1)); 77 | } 78 | 79 | #[test] 80 | fn test_waitings() { 81 | let wg = WaitGroup::new(); 82 | wg.add(1); 83 | wg.add(1); 84 | assert_eq!(wg.waitings(), 2); 85 | } 86 | --------------------------------------------------------------------------------