adaptive-barrier-1.0.0/.cargo_vcs_info.json0000644000000001120000000000000142440ustar { "git": { "sha1": "db33a43e7248204c05b86d9f3ed92dc6eaf425fe" } } adaptive-barrier-1.0.0/.github/codecov.yml000064400000000000000000000002150000000000000165230ustar 00000000000000comment: layout: "diff, flags, files" require_changes: true coverage: status: project: default: informational: true adaptive-barrier-1.0.0/.github/workflows/coverage.yaml000064400000000000000000000020240000000000000210720ustar 00000000000000name: Test coverage on: push: branches: - main pull_request: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: full jobs: coverage: name: Coverage runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: nightly profile: minimal default: true - name: Restore cache uses: Swatinem/rust-cache@v1 - name: Run cargo-tarpaulin uses: actions-rs/tarpaulin@v0.1 with: args: '--all-features --run-types Doctests,Tests' timeout: 120 - name: Upload to codecov.io uses: codecov/codecov-action@239febf655bba88b16ff5dea1d3135ea8663a1f9 with: token: ${{ secrets.CODECOV_TOKEN }} - name: Archive code coverage results uses: actions/upload-artifact@v2 with: name: code-coverage-report path: cobertura.xml retention-days: 30 adaptive-barrier-1.0.0/.github/workflows/test.yaml000064400000000000000000000041600000000000000202610ustar 00000000000000name: test on: push: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: full jobs: test: name: Build & test strategy: fail-fast: false matrix: os: - ubuntu-latest - macos-latest - windows-latest rust: - stable - beta - nightly - 1.26.0 - 1.31.0 runs-on: ${{ matrix.os }} steps: - name: checkout uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} default: true profile: minimal - name: Restore cache uses: Swatinem/rust-cache@v1 - name: Build & test env: RUST_VERSION: ${{ matrix.rust }} OS: ${{ matrix.os }} RUSTFLAGS: -D warnings run: cargo test rustfmt: name: Check formatting runs-on: ubuntu-latest steps: - name: checkout uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable default: true components: rustfmt - run: cargo fmt --all -- --check links: name: Check documentation links runs-on: ubuntu-latest steps: - name: checkout uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable default: true - name: Restore cache uses: Swatinem/rust-cache@v1 - name: Check links run: cargo rustdoc --all-features -- -D warnings clippy: name: Clippy lints runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal default: true components: clippy - name: Restore cache uses: Swatinem/rust-cache@v1 - name: Run clippy linter run: cargo clippy --all --tests -- -D clippy::all -D warnings adaptive-barrier-1.0.0/.gitignore000064400000000000000000000000300000000000000150010ustar 00000000000000/target Cargo.lock tags adaptive-barrier-1.0.0/CHANGELOG.md000064400000000000000000000001120000000000000146230ustar 00000000000000# 1.0.0 * Releasing as stable (no changes). # 0.1.0 * Initial release. adaptive-barrier-1.0.0/Cargo.toml0000644000000016770000000000000122630ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "adaptive-barrier" version = "1.0.0" authors = ["Michal 'vorner' Vaner "] description = "Barrier with adaptable number of thread subsciptions" documentation = "https://docs.rs/adaptive-barrier" readme = "README.md" keywords = ["barrier", "sync", "panic"] categories = ["concurrency", "algorithms"] license = "Apache-2.0/MIT" repository = "https://github.com/vorner/adaptive-barrier" [dependencies] adaptive-barrier-1.0.0/Cargo.toml.orig000064400000000000000000000010240000000000000157040ustar 00000000000000[package] name = "adaptive-barrier" version = "1.0.0" authors = ["Michal 'vorner' Vaner "] description = "Barrier with adaptable number of thread subsciptions" documentation = "https://docs.rs/adaptive-barrier" repository = "https://github.com/vorner/adaptive-barrier" readme = "README.md" keywords = ["barrier", "sync", "panic"] categories = ["concurrency", "algorithms"] license = "Apache-2.0/MIT" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] adaptive-barrier-1.0.0/LICENSE-APACHE000064400000000000000000000251370000000000000147540ustar 00000000000000 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. adaptive-barrier-1.0.0/LICENSE-MIT000064400000000000000000000020470000000000000144570ustar 00000000000000Copyright (c) 2017 arc-swap developers Permission 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. adaptive-barrier-1.0.0/README.md000064400000000000000000000021530000000000000143000ustar 00000000000000# Adaptive barrier [![Actions Status](https://github.com/vorner/adaptive-barrier/workflows/test/badge.svg)](https://github.com/vorner/adaptive-barrier/actions) [![codecov](https://codecov.io/gh/vorner/adaptive-barrier/branch/main/graph/badge.svg?token=0FhwzST2nI)](https://codecov.io/gh/vorner/adaptive-barrier) [![docs](https://docs.rs/adaptive-barrier/badge.svg)](https://docs.rs/adaptive-barrier) A Barrier synchronization primitive, similar to `std::sync::Barrier`, but one that adjusts the expected number of threads. This makes it robust in face of panics (it won't make your program deadlock, like the standard `Barrier`). ## 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. adaptive-barrier-1.0.0/src/lib.rs000064400000000000000000000344100000000000000147250ustar 00000000000000//! A synchronization barrier that adapts to the number of subscribing threads. //! //! This has the same goal as the [`std::sync::Barrier`], but it handles runtime additions //! or removals of thread subscriptions ‒ the number of threads waiting for the barrier can change //! (even while some threads are already waiting). //! //! It can be convenient if your algorithm changes the number of working threads during lifetime. //! You don't need a different barrier for different phases of the algorithm. //! //! But most importantly, the [`Barrier`] is robust in face of panics. //! //! # Problems with panics and the [`std::sync::Barrier`] //! //! If we have a barrier that was set up for `n` threads, some of the threads park on it and wait //! for the rest to finish, but one of the other threads has a bug and panics, the already parked //! threads will never get a chance to continue and the whole algorithm deadlocks. This is usually //! worse than propagating the panic and cleaning up the whole algorithm or even shutting down the //! whole application, because then something can recover by restarting it. If the application //! deadlocks in the computation phase, but otherwise looks healthy, it will never recover. //! //! This makes applications less robust and makes tests which use barriers very annoying and //! fragile to write. //! //! Our [`Barrier`] watches the number of subscribed threads (by counting the number of its own //! clones, unlike the standard barrier, this one can and need to be cloned for each thread). If a //! thread disappears (or is added), the expectations are adjusted. //! //! It also has a mode in which it'll get poisoned and propagate the panic to the rest of the //! group. #![doc(test(attr(deny(warnings))))] #![forbid(unsafe_code)] #![warn(missing_docs)] use std::fmt::{Debug, Formatter, Result as FmtResult}; use std::mem; use std::panic::UnwindSafe; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use std::thread; /// What to do if a [`Barrier`] is destroyed during a panic. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum PanicMode { /// Nothing special. /// /// Just decrement the number of expected threads, just like during any normal destruction. Decrement, /// Poison the barrier. /// /// All calls to [`wait`][Barrier::wait], including the ones that are already in progress, will /// panic too. Once poisoned, there's no way to "unpoison" the barrier. /// /// This is useful in case a failure in one thread makes the whole group unusable (very often /// in tests). Poison, } /// A result after waiting. /// /// This can be used to designate a single thread as the leader after calling /// [`wait`][Barrier::wait]. #[derive(Debug)] pub struct WaitResult { is_leader: bool, } impl WaitResult { /// Returns true for exactly one thread from a waiting group. /// /// An algorithm can use that to pick a thread between equals that'll do some singleton thing /// (consolidate the results, for example). pub fn is_leader(&self) -> bool { self.is_leader } } struct Inner { active: usize, waiting: usize, gen: usize, leader: bool, poisoned: bool, } impl Inner { fn check_release(&mut self) -> bool { if self.waiting >= self.active || self.poisoned { self.leader = true; self.gen = self.gen.wrapping_add(1); self.waiting = 0; true } else { false } } } struct Shared { inner: Mutex, condvar: Condvar, panic_mode: PanicMode, } /// A Barrier to synchronize multiple threads. /// /// Multiple threads can meet on a single barrier to synchronize a "meeting point" in a computation /// (eg. when they need to pass results to others), much like the [`Barrier`][std::sync::Barrier] /// from the standard library. /// /// Unlike that, the expected number of threads waiting for the barrier is not preset in the `new` /// call, but autodetected and adapted to at runtime. /// /// The way this is done is by cloning the original [`Barrier`] ‒ for a group to continue after /// wait, a [`wait`][Barrier::wait] needs to be called on each clone. This allows to add or remove /// (even implicitly by panicking) the clones as needed. /// /// # Examples /// /// ```rust /// # use std::thread; /// # use adaptive_barrier::{Barrier, PanicMode}; /// /// let barrier = Barrier::new(PanicMode::Poison); /// let mut threads = Vec::new(); /// for _ in 0..4 { /// // Each thread gets its own clone of the barrier. They are tied together, not independent. /// let mut barrier = barrier.clone(); /// let thread = thread::spawn(move || { /// // Wait to start everything at the same time /// barrier.wait(); /// /// // ... Do some work that needs to start synchronously ... /// // Now, if this part panics, it will *not* deadlock, it'll unlock the others just fine /// // and propagate the panic (see the parameter to new(..) /// /// // Wait for all threads to finish /// if barrier.wait().is_leader() { /// // Pick one thread to consolidate the results here /// /// // Note that as we don't call wait any more, if we panic here, it'll not get /// // propagated through the barrier any more. /// } /// }); /// threads.push(thread); /// } /// /// // Watch out for the last instance here in the main/controlling thread. You can either call /// // wait on it too, or make sure it is dropped. If you don't, others will keep waiting for it. /// drop(barrier); /// /// for thread in threads { /// thread.join().expect("Propagating thread panic"); /// } /// ``` pub struct Barrier(Arc); impl Barrier { /// Creates a new (independent) barrier. /// /// To create more handles to the same barrier, clone it. /// /// The panic mode specifies what to do if a barrier observes a panic (is dropped while /// panicking). pub fn new(panic_mode: PanicMode) -> Self { Barrier(Arc::new(Shared { inner: Mutex::new(Inner { active: 1, // this thread waiting: 0, gen: 0, leader: false, poisoned: false, }), condvar: Condvar::new(), panic_mode, })) } fn check_release(&self, lock: &mut MutexGuard<'_, Inner>) { if lock.check_release() { self.0.condvar.notify_all(); } } /// Wait for all the other threads to wait too. /// /// This'll block until all threads holding clones of the same barrier call `wait`. /// /// # Panics /// /// If the barrier was created with [`PanicMode::Poison`] and some other clone of the barrier /// observed a panic, this'll also panic (even if it was already parked inside). pub fn wait(&mut self) -> WaitResult { let mut lock = self.0.inner.lock().unwrap(); lock.waiting += 1; let gen = lock.gen; self.check_release(&mut lock); while gen == lock.gen { lock = self.0.condvar.wait(lock).unwrap(); } if lock.poisoned { drop(lock); // Make sure we don't poison the mutex too panic!("Barrier is poisoned"); } WaitResult { is_leader: mem::replace(&mut lock.leader, false), } } } impl Clone for Barrier { fn clone(&self) -> Self { let new = Arc::clone(&self.0); new.inner.lock().unwrap().active += 1; Barrier(new) } } impl Drop for Barrier { fn drop(&mut self) { let mut lock = self.0.inner.lock().unwrap(); lock.active -= 1; if self.0.panic_mode == PanicMode::Poison && thread::panicking() { lock.poisoned = true; } self.check_release(&mut lock); } } impl Debug for Barrier { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { fmt.pad("Barrier { .. }") } } impl Default for Barrier { fn default() -> Self { Self::new(PanicMode::Decrement) } } // We deal with panics explicitly. impl UnwindSafe for Barrier {} #[cfg(test)] mod tests { use std::panic; use std::sync::atomic::Ordering::*; use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::thread::{self, sleep}; use std::time::Duration; use super::*; /// When we have just one instance, it doesn't wait. #[test] fn single() { let mut bar = Barrier::new(PanicMode::Decrement); assert!(bar.wait().is_leader()); } /// Check the barriers wait for each other. #[test] fn dispatch() { let mut bar = Barrier::new(PanicMode::Decrement); let waited = Arc::new(AtomicBool::new(false)); let t = thread::spawn({ let mut bar = bar.clone(); let waited = Arc::clone(&waited); move || { bar.wait(); waited.store(true, SeqCst); bar.wait(); } }); sleep(Duration::from_millis(50)); assert!(!waited.load(SeqCst)); bar.wait(); bar.wait(); assert!(waited.load(SeqCst)); t.join().unwrap(); } #[test] fn adjust_up() { let mut bar = Barrier::new(PanicMode::Decrement); let woken = Arc::new(AtomicUsize::new(0)); let t1 = thread::spawn({ let mut bar = bar.clone(); let woken = Arc::clone(&woken); move || { bar.wait(); woken.fetch_add(1, SeqCst); bar.wait(); } }); sleep(Duration::from_millis(50)); assert_eq!(woken.load(SeqCst), 0); let t2 = thread::spawn({ let mut bar = bar.clone(); let woken = Arc::clone(&woken); move || { bar.wait(); woken.fetch_add(1, SeqCst); bar.wait(); } }); sleep(Duration::from_millis(50)); assert_eq!(woken.load(SeqCst), 0); bar.wait(); bar.wait(); assert_eq!(woken.load(SeqCst), 2); t1.join().unwrap(); t2.join().unwrap(); } #[test] fn adjust_down() { let mut bar = Barrier::new(PanicMode::Decrement); let woken = Arc::new(AtomicUsize::new(0)); let t1 = thread::spawn({ let mut bar = bar.clone(); let woken = Arc::clone(&woken); move || { bar.wait(); woken.fetch_add(1, SeqCst); bar.wait(); } }); let t2 = thread::spawn({ let mut bar = bar.clone(); let woken = Arc::clone(&woken); move || { // Only one wait, the second one will be done on only 2 copies bar.wait(); woken.fetch_add(1, SeqCst); } }); sleep(Duration::from_millis(50)); assert_eq!(woken.load(SeqCst), 0); bar.wait(); t2.join().unwrap(); bar.wait(); assert_eq!(woken.load(SeqCst), 2); t1.join().unwrap(); } #[test] fn adjust_panic() { let mut bar = Barrier::new(PanicMode::Decrement); let woken = Arc::new(AtomicUsize::new(0)); let t1 = thread::spawn({ let mut bar = bar.clone(); let woken = Arc::clone(&woken); move || { bar.wait(); woken.fetch_add(1, SeqCst); bar.wait(); woken.fetch_add(1, SeqCst); } }); let t2 = thread::spawn({ let mut bar = bar.clone(); let woken = Arc::clone(&woken); move || { // Only one wait, the second one will be done on only 2 copies bar.wait(); woken.fetch_add(1, SeqCst); panic!("We are going to panic, woohooo, the thing still adjusts"); } }); sleep(Duration::from_millis(50)); assert_eq!(woken.load(SeqCst), 0); bar.wait(); t2.join().unwrap_err(); bar.wait(); t1.join().unwrap(); assert_eq!(woken.load(SeqCst), 3); } #[test] fn adjust_drop() { let bar = Barrier::new(PanicMode::Decrement); let woken = Arc::new(AtomicUsize::new(0)); let t1 = thread::spawn({ let mut bar = bar.clone(); let woken = Arc::clone(&woken); move || { bar.wait(); woken.fetch_add(1, SeqCst); bar.wait(); } }); sleep(Duration::from_millis(50)); assert_eq!(woken.load(SeqCst), 0); let t2 = thread::spawn({ let mut bar = bar.clone(); let woken = Arc::clone(&woken); move || { bar.wait(); woken.fetch_add(1, SeqCst); bar.wait(); } }); sleep(Duration::from_millis(50)); assert_eq!(woken.load(SeqCst), 0); drop(bar); t1.join().unwrap(); t2.join().unwrap(); assert_eq!(woken.load(SeqCst), 2); } /// Poisoning of the barrier. #[test] #[cfg_attr(clippy, allow(clippy::redundant_clone))] fn poisoning() { let mut bar = Barrier::new(PanicMode::Poison); let woken = Arc::new(AtomicUsize::new(0)); let t1 = thread::spawn({ let mut bar = bar.clone(); let woken = Arc::new(AtomicUsize::new(0)); move || { bar.wait(); woken.fetch_add(1, SeqCst); bar.wait(); } }); sleep(Duration::from_millis(50)); assert_eq!(woken.load(SeqCst), 0); let t2 = thread::spawn({ let bar = bar.clone(); move || { // Make sure this one gets into the closure so we destroy it on the panic. // Not issue in practice where it would get pulled in by .wait(), but we don't have // one here in test. let _bar = bar; panic!("Testing a panic"); } }); // The thread 2 panics t2.join().unwrap_err(); // And the panic propagates to t1, even though we still hold our copy of barrier. t1.join().unwrap_err(); // Our last instance would panic too. panic::catch_unwind(move || bar.wait()).unwrap_err(); } }