synchronoise-1.0.1/.cargo_vcs_info.json0000644000000001360000000000100135560ustar { "git": { "sha1": "3012fc82ccd47e13287610b66556dba4638f2f57" }, "path_in_vcs": "" }synchronoise-1.0.1/.gitignore000064400000000000000000000000300072674642500143570ustar 00000000000000target Cargo.lock *.swp synchronoise-1.0.1/.travis.yml000064400000000000000000000003130072674642500145040ustar 00000000000000language: rust cache: cargo rust: - stable - beta - nightly script: - cargo build --verbose - cargo test --verbose -- --test-threads=1 --nocapture matrix: allow_failures: - rust: nightly synchronoise-1.0.1/CHANGELOG.md000064400000000000000000000026010072674642500142060ustar 00000000000000# changelog for synchronoise ## [0.4.0] - 2017-11-02 ### Changed - `SignalEvent` and `CountdownEvent` have been updated to not use `Mutex`es internally - In the refactor, `wait_timeout` was changed to always wait for the full duration if the signal was never set, so the return value has been changed to reflect this. This is a **breaking change** - In the refactor, `CountdownEvent` was changed so that its counter is now is `usize` instead of an `isize`. Since it's an invalid state for the counter to be below zero, let's encode that in the type. This is a **breaking change** if you were directly using the counter value or its type before ## [0.3.0] - 2017-03-06 ### Added - `CountdownEvent::guard` and `CountdownGuard`, to provide scope-based increment/decrement - `WriterReaderPhaser`, a primitive that allows multiple wait-free "writer critical sections" against a "reader phase flip" that waits for currently-active writers to finish - also the related structs `PhaserCriticalSection` and `PhaserReadLock` ## [0.2.0] - 2017-02-28 ### Added - `CountdownEvent::wait_timeout`, to wait but also have a timeout - `SignalEvent`, a primitive that lets one or more threads wait for a signal from another one ## [0.1.0] - 2017-02-27 ### Added - `CountdownEvent`, a primitive that keeps a counter that allows you to block until it hits zero synchronoise-1.0.1/Cargo.toml0000644000000021650000000000100115600ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] name = "synchronoise" version = "1.0.1" authors = ["QuietMisdreavus "] description = "Synchronization primitives that build upon the standard library" documentation = "https://docs.rs/synchronoise/" readme = "README.md" keywords = [ "synchronization", "parallel_programming", "phaser", ] categories = ["concurrency"] license = "MIT OR Apache-2.0" repository = "https://github.com/QuietMisdreavus/synchronoise" [dependencies.crossbeam-queue] version = "0.3.5" [badges.appveyor] repository = "QuietMisdreavus/synchronoise" [badges.maintenance] status = "as-is" [badges.travis-ci] repository = "QuietMisdreavus/synchronoise" synchronoise-1.0.1/Cargo.toml.orig000064400000000000000000000011640072674642500152670ustar 00000000000000[package] name = "synchronoise" version = "1.0.1" authors = ["QuietMisdreavus "] description = "Synchronization primitives that build upon the standard library" repository = "https://github.com/QuietMisdreavus/synchronoise" documentation = "https://docs.rs/synchronoise/" license = "MIT OR Apache-2.0" categories = ["concurrency"] keywords = ["synchronization", "parallel_programming", "phaser"] [badges] travis-ci = { repository = "QuietMisdreavus/synchronoise" } appveyor = { repository = "QuietMisdreavus/synchronoise" } maintenance = { status = "as-is" } [dependencies] crossbeam-queue = "0.3.5" synchronoise-1.0.1/LICENSE-APACHE000064400000000000000000000261360072674642500143320ustar 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. synchronoise-1.0.1/LICENSE-MIT000064400000000000000000000020730072674642500140340ustar 00000000000000MIT License Copyright (c) 2017 synchronoise contributors 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. synchronoise-1.0.1/README.md000064400000000000000000000032440072674642500136600ustar 00000000000000# synchronoise fun synchronization primitives for your fun synchronization needs [![Build Status](https://travis-ci.org/QuietMisdreavus/synchronoise.svg?branch=master)](https://travis-ci.org/QuietMisdreavus/synchronoise) [![Build status](https://ci.appveyor.com/api/projects/status/222hqcyigcdihfw9/branch/master?svg=true)](https://ci.appveyor.com/project/QuietMisdreavus/synchronoise/branch/master) [Documentation](https://docs.rs/synchronoise) | ([Manually-generated docs for master][doc-dev]) [doc-dev]: https://tonberry.quietmisdreavus.net/synchronoise-dev/synchronoise/ This is a collection of synchronization facilities that aren't part of the standard library that I wanted to make sure were available for the Rust community. This crate contains the following synchronization primitives: * `CountdownEvent`, a port of `System.Threading.CountdownEvent` from .NET (also called `CountDownLatch` in Java). * `SignalEvent`, a port of `System.Threading.EventWaitHandle` (and its derived classes, `AutoResetEvent` and `ManualResetEvent`) from .NET. * `WriterReaderPhaser`, a port of `WriterReaderPhaser` from HdrHistogram. To add this crate to your project, add the following line to your Cargo.toml: ```toml [dependencies] synchronoise = "0.4.0" ``` ...and the following to your crate root: ```rust extern crate synchronoise; ``` # License synchronoise is licensed under either the MIT License or the Apache License version 2.0, at your option. See the files `LICENSE-MIT` and `LICENSE-APACHE` for details. (synchronoise is named after [a move in Pokemon][synch], by the way) [synch]: http://bulbapedia.bulbagarden.net/wiki/Synchronoise_(move) synchronoise-1.0.1/appveyor.yml000064400000000000000000000024430072674642500147710ustar 00000000000000environment: RUSTUP_INIT_SKIP_MSVC_CHECK: '1' matrix: - TARGET: stable-x86_64-pc-windows-msvc - TARGET: stable-i686-pc-windows-msvc - TARGET: beta-x86_64-pc-windows-msvc - TARGET: beta-i686-pc-windows-msvc - TARGET: nightly-x86_64-pc-windows-msvc - TARGET: nightly-i686-pc-windows-msvc - TARGET: stable-i686-pc-windows-gnu MSYS_BITS: 32 - TARGET: stable-x86_64-pc-windows-gnu MSYS_BITS: 64 - TARGET: beta-x86_64-pc-windows-gnu MSYS_BITS: 64 - TARGET: beta-i686-pc-windows-gnu MSYS_BITS: 32 - TARGET: nightly-x86_64-pc-windows-gnu MSYS_BITS: 64 - TARGET: nightly-i686-pc-windows-gnu MSYS_BITS: 32 matrix: allow_failures: - TARGET: nightly-x86_64-pc-windows-msvc - TARGET: nightly-i686-pc-windows-msvc - TARGET: nightly-x86_64-pc-windows-gnu - TARGET: nightly-i686-pc-windows-gnu cache: - '%USERPROFILE%\.cargo -> Cargo.toml' - '%USERPROFILE%\.rustup' install: - curl -sSf -o rustup-init.exe https://win.rustup.rs/ - rustup-init.exe -y --default-toolchain %TARGET% - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - if defined MSYS_BITS set PATH=C:\msys64\mingw%MSYS_BITS%\bin;C:\msys64\usr\bin;%PATH% - rustc -vV - cargo -vV build_script: - cargo build --verbose test_script: - cargo test --verbose -- --test-threads=1 --nocapture synchronoise-1.0.1/src/event.rs000064400000000000000000000542050072674642500146620ustar 00000000000000//! "Event" primitives, allowing one thread to wait on a signal or countdown from other threads. //! //! The primary types in this module are the [`CountdownEvent`] and the [`SignalEvent`] structs. See //! the documentation on those types for further information. //! //! [`CountdownEvent`]: struct.CountdownEvent.html //! [`SignalEvent`]: struct.SignalEvent.html use std::convert::identity; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::thread; use std::time::Duration; use crossbeam_queue::SegQueue; /// A synchronization primitive that signals when its count reaches zero. /// /// With a `CountdownEvent`, it's possible to cause one thread to wait on a set of computations /// occurring in other threads by making the other threads interact with the counter as they /// perform their work. /// /// The main limitation of a CountdownEvent is that once its counter reaches zero (even by starting /// there), any attempts to update the counter will return `CountdownError::AlreadySet` until the /// counter is reset by calling `reset` or `reset_to_count`. /// /// `CountdownEvent` is a port of [System.Threading.CountdownEvent][src-link] from .NET (also /// called [`CountDownLatch`][java-src] in Java). /// /// [src-link]: https://msdn.microsoft.com/en-us/library/system.threading.countdownevent(v=vs.110).aspx /// [java-src]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html /// /// # Example /// /// This example uses a `CountdownEvent` to make the "coordinator" thread sleep until all of its /// "worker" threads have finished. Each thread calls `signal.decrement()` to signal to the Event /// that its work has completed. When the last thread does this (and brings the counter to zero), /// the "coordinator" thread wakes up and prints `all done!`. /// /// ``` /// use synchronoise::CountdownEvent; /// use std::sync::Arc; /// use std::thread; /// use std::time::Duration; /// /// let thread_count = 5; /// let counter = Arc::new(CountdownEvent::new(thread_count)); /// /// for i in 0..thread_count { /// let signal = counter.clone(); /// thread::spawn(move || { /// thread::sleep(Duration::from_secs(i as u64)); /// println!("thread {} activated!", i); /// signal.decrement().unwrap(); /// }); /// } /// /// counter.wait(); /// /// println!("all done!"); /// ``` pub struct CountdownEvent { initial: usize, counter: AtomicUsize, waiting: SegQueue, } /// The collection of errors that can be returned by [`CountdownEvent`] methods. /// /// See [`CountdownEvent`] for more details. /// /// [`CountdownEvent`]: struct.CountdownEvent.html #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum CountdownError { /// Returned when adding to a counter would have caused it to overflow. SaturatedCounter, /// Returned when attempting to signal would have caused the counter to go below zero. TooManySignals, /// Returned when attempting to modify the counter after it has reached zero. AlreadySet, } impl CountdownEvent { /// Creates a new `CountdownEvent`, initialized to the given count. /// /// Remember that once the counter reaches zero, calls to `add` or `signal` will fail, so /// passing zero to this function will create a `CountdownEvent` that is permanently signaled. pub fn new(count: usize) -> CountdownEvent { CountdownEvent { initial: count, counter: AtomicUsize::new(count), waiting: SegQueue::new(), } } /// Resets the counter to the count given to `new`. /// /// This function is safe because the `&mut self` enforces that no other references or locks /// exist. pub fn reset(&mut self) { self.counter = AtomicUsize::new(self.initial); // there shouldn't be any remaining thread handles in here, but let's clear it out anyway while let Some(thread) = self.waiting.pop() { thread.unpark(); } } /// Resets the counter to the given count. /// /// This function is safe because the `&mut self` enforces that no other references or locks /// exist. pub fn reset_to_count(&mut self, count: usize) { self.initial = count; self.reset(); } /// Returns the current counter value. pub fn count(&self) -> usize { self.counter.load(Ordering::SeqCst) } /// Adds the given count to the counter. /// /// # Errors /// /// If the counter is already at zero, this function will return `CountdownError::AlreadySet`. /// /// If the given count would cause the counter to overflow `usize`, this function will return /// `CountdownError::SaturatedCounter`. pub fn add(&self, count: usize) -> Result<(), CountdownError> { let mut current = self.count(); loop { if current == 0 { return Err(CountdownError::AlreadySet); } if let Some(new_count) = current.checked_add(count) { let exchange_result = self.counter.compare_exchange_weak( current, new_count, Ordering::SeqCst, Ordering::SeqCst, ); match exchange_result { Ok(_) => return Ok(()), Err(last_count) => current = last_count, } } else { return Err(CountdownError::SaturatedCounter); } } } /// Subtracts the given count to the counter, and returns whether this caused any waiting /// threads to wake up. /// /// # Errors /// /// If the counter is already at zero, this function will return `CountdownError::AlreadySet`. /// /// If the given count would cause the counter to go *below* zero (instead of reaching zero), /// this function will return `CountdownError::TooManySignals`. pub fn signal(&self, count: usize) -> Result { let mut current = self.count(); loop { if current == 0 { return Err(CountdownError::AlreadySet); } if let Some(new_count) = current.checked_sub(count) { let exchange_result = self.counter.compare_exchange_weak( current, new_count, Ordering::SeqCst, Ordering::SeqCst, ); match exchange_result { Ok(_) => { current = new_count; break; } Err(last_count) => current = last_count, } } else { return Err(CountdownError::TooManySignals); } } if current == 0 { while let Some(thread) = self.waiting.pop() { thread.unpark(); } Ok(true) } else { Ok(false) } } /// Adds one to the count. /// /// # Errors /// /// See [`add`] for the situations where this function will return an error. /// /// [`add`]: #method.add pub fn increment(&self) -> Result<(), CountdownError> { self.add(1) } /// Subtracts one from the counter, and returns whether this caused any waiting threads to wake /// up. /// /// # Errors /// /// See [`signal`] for the situations where this function will return an error. /// /// [`signal`]: #method.signal pub fn decrement(&self) -> Result { self.signal(1) } /// Increments the counter, then returns a guard object that will decrement the counter upon /// drop. /// /// # Errors /// /// This function will return the same errors as `add`. If the event has already signaled by /// the time the guard is dropped (and would cause its `decrement` call to return an error), /// then the error will be silently ignored. /// /// # Example /// /// Here's the sample from the main docs, using `CountdownGuard`s instead of manually /// decrementing: /// /// ``` /// use synchronoise::CountdownEvent; /// use std::sync::Arc; /// use std::thread; /// use std::time::Duration; /// /// let thread_count = 5; /// // counter can't start from zero, but the guard increments on its own, so start at one and /// // just decrement once when we're ready to wait /// let counter = Arc::new(CountdownEvent::new(1)); /// /// for i in 0..thread_count { /// let signal = counter.clone(); /// thread::spawn(move || { /// let _guard = signal.guard().unwrap(); /// thread::sleep(Duration::from_secs(i)); /// println!("thread {} activated!", i); /// }); /// } /// /// // give all the threads time to increment the counter before continuing /// thread::sleep(Duration::from_millis(100)); /// counter.decrement().unwrap(); /// counter.wait(); /// /// println!("all done!"); /// ``` pub fn guard(&self) -> Result { CountdownGuard::new(self) } /// Blocks the current thread until the counter reaches zero. /// /// This function will block indefinitely until the counter reaches zero. It will return /// immediately if it is already at zero. pub fn wait(&self) { // see SignalEvent::wait for why we push first even if the count is already set self.waiting.push(thread::current()); let mut first = true; while self.count() > 0 { if first { first = false; } else { self.waiting.push(thread::current()); } thread::park(); } } /// Blocks the current thread until the timer reaches zero, or until the given timeout elapses, /// returning the count at the time of wakeup. /// /// This function will return immediately if the counter was already at zero. Otherwise, it /// will block for roughly no longer than `timeout`, or when the counter reaches zero, /// whichever comes first. pub fn wait_timeout(&self, timeout: Duration) -> usize { use std::time::Instant; // see SignalEvent::wait for why we push first even if the count is already set self.waiting.push(thread::current()); let begin = Instant::now(); let mut first = true; let mut remaining = timeout; loop { let current = self.count(); if current == 0 { return 0; } if first { first = false; } else { let elapsed = begin.elapsed(); if elapsed >= timeout { return current; } else { remaining = timeout - elapsed; } self.waiting.push(thread::current()); } thread::park_timeout(remaining); } } } /// An opaque guard struct that decrements the count of a borrowed `CountdownEvent` on drop. /// /// See [`CountdownEvent::guard`] for more information about this struct. /// /// [`CountdownEvent::guard`]: struct.CountdownEvent.html#method.guard pub struct CountdownGuard<'a> { event: &'a CountdownEvent, } impl<'a> CountdownGuard<'a> { fn new(event: &'a CountdownEvent) -> Result, CountdownError> { event.increment()?; Ok(CountdownGuard { event }) } } /// Upon drop, this guard will decrement the counter of its parent `CountdownEvent`. If this would /// cause an error (see [`CountdownEvent::signal`] for details), the error is silently ignored. /// /// [`CountdownEvent::signal`]: struct.CountdownEvent.html#method.signal impl<'a> Drop for CountdownGuard<'a> { fn drop(&mut self) { // if decrement() returns an error, then the event has already been signaled somehow. i'm // not gonna care about it tho self.event.decrement().ok(); } } /// Determines the reset behavior of a [`SignalEvent`]. /// /// See [`SignalEvent`] for more information. /// /// [`SignalEvent`]: struct.SignalEvent.html #[derive(Debug, PartialEq, Copy, Clone)] pub enum SignalKind { /// An activated `SignalEvent` automatically resets when a thread is resumed. /// /// `SignalEvent`s with this kind will only resume one thread at a time. Auto, /// An activated `SignalEvent` must be manually reset to block threads again. /// /// `SignalEvent`s with this kind will signal every waiting thread to continue at once. Manual, } /// A synchronization primitive that allows one or more threads to wait on a signal from another /// thread. /// /// With a `SignalEvent`, it's possible to have one or more threads gate on a signal from another /// thread. The behavior for what happens when an event is signaled depends on the value of the /// `signal_kind` parameter given to `new`, or whether `auto` or `manual` is used to construct the /// `SignalEvent`: /// /// * A value of `SignalKind::Auto` (or a `SignalEvent` created via `SignalEvent::auto()`) will /// automatically reset the signal when a thread is resumed by this event. If more than one /// thread is waiting on the event when it is signaled, only one will be resumed. /// * A value of `SignalKind::Manual` (or a `SignalEvent` created via `SignalEvent::manual()`) will /// remain signaled until it is manually reset. If more than one thread is waiting on the event /// when it is signaled, all of them will be resumed. Any other thread that tries to wait on the /// signal before it is reset will not be blocked at all. /// /// `SignalEvent` is a port of [System.Threading.EventWaitHandle][src-link] from .NET. /// /// [src-link]: https://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle(v=vs.110).aspx /// /// # Example /// /// The following example uses two `SignalEvent`s: /// /// * `start_signal` is used as a kind of `std::sync::Barrier`, that keeps all the threads inside /// the loop from starting until they all have been spawned. All the `start.wait()` calls resume /// when `start_signal.signal()` is called after the initial loop. /// * Note that because the "coordinator" doesn't wait for each thread to be scheduled before /// signaling, it's possible that some later threads may not have had a chance to enter /// `start.wait()` before the signal is set. In this case they won't block in the first place, /// and immediately return. /// * `stop_signal` is used to wake up the "coordinator" thread when each "worker" thread is /// finished with its work. This allows it to keep a count of the number of threads yet to /// finish, so it can exit its final loop when all the threads have stopped. /// /// ``` /// use synchronoise::SignalEvent; /// use std::sync::Arc; /// use std::thread; /// use std::time::Duration; /// /// let start_signal = Arc::new(SignalEvent::manual(false)); /// let stop_signal = Arc::new(SignalEvent::auto(false)); /// let mut thread_count = 5; /// /// for i in 0..thread_count { /// let start = start_signal.clone(); /// let stop = stop_signal.clone(); /// thread::spawn(move || { /// // as a Manual-reset signal, all the threads will start at the same time /// start.wait(); /// thread::sleep(Duration::from_secs(i)); /// println!("thread {} activated!", i); /// stop.signal(); /// }); /// } /// /// start_signal.signal(); /// /// while thread_count > 0 { /// // as an Auto-reset signal, this will automatically reset when resuming /// // so when the loop comes back, we don't have to reset before blocking again /// stop_signal.wait(); /// thread_count -= 1; /// } /// /// println!("all done!"); /// ``` pub struct SignalEvent { reset: SignalKind, signal: AtomicBool, waiting: SegQueue, } impl SignalEvent { /// Creates a new `SignalEvent` with the given starting state and reset behavior. /// /// If `init_state` is `true`, then this `SignalEvent` will start with the signal already set, /// so that threads that wait will immediately unblock. pub fn new(init_state: bool, signal_kind: SignalKind) -> SignalEvent { SignalEvent { reset: signal_kind, signal: AtomicBool::new(init_state), waiting: SegQueue::new(), } } /// Creates a new automatically-resetting `SignalEvent` with the given starting state. /// /// If `init_state` is `true`, then this `SignalEvent` will start with the signal already set, /// so that the first thread that tries to wait will immediately unblock. pub fn auto(init_state: bool) -> SignalEvent { SignalEvent::new(init_state, SignalKind::Auto) } /// Creates a new manually-resetting `SignalEvent` with the given starting state. /// /// If `init_state` is `true`, then this `SignalEvent` will start with the signal alraedy set, /// so that threads that wait will immediately unblock until `reset` is called. pub fn manual(init_state: bool) -> SignalEvent { SignalEvent::new(init_state, SignalKind::Manual) } /// Returns the current signal status of the `SignalEvent`. pub fn status(&self) -> bool { self.signal.load(Ordering::SeqCst) } /// Sets the signal on this `SignalEvent`, potentially waking up one or all threads waiting on /// it. /// /// If more than one thread is waiting on the event, the behavior is different depending on the /// `SignalKind` passed to the event when it was created. For a value of `Auto`, one thread /// will be resumed. For a value of `Manual`, all waiting threads will be resumed. /// /// If no thread is currently waiting on the event, its state will be set regardless. Any /// future attempts to wait on the event will unblock immediately, except for a `SignalKind` of /// Auto, which will immediately unblock the first thread only. pub fn signal(&self) { self.signal.store(true, Ordering::SeqCst); match self.reset { // there may be duplicate handles in the queue due to spurious wakeups, so just loop // until we know the signal got reset - any that got woken up wrongly will also observe // the reset signal and push their handle back in SignalKind::Auto => { while self.signal.load(Ordering::SeqCst) { if let Some(thread) = self.waiting.pop() { thread.unpark(); } else { break; } } } // for manual resets, just unilaterally drain the queue SignalKind::Manual => { while let Some(thread) = self.waiting.pop() { thread.unpark(); } } } } /// Resets the signal on this `SignalEvent`, allowing threads that wait on it to block. pub fn reset(&self) { self.signal.store(false, Ordering::SeqCst); } /// Blocks this thread until another thread calls `signal`. /// /// If this event is already set, then this function will immediately return without blocking. /// For events with a `SignalKind` of `Auto`, this will reset the signal so that the next /// thread to wait will block. pub fn wait(&self) { // Push first, regardless, because in SignalEvent's doctest there's a thorny race condition // where (1) the waiting thread will see an unset signal, (2) the signalling thread will // set the signal and drain the queue, and only then (3) the waiting thread will push its // handle. Having erroneous handles is ultimately harmless from a correctness standpoint // because signal loops properly anyway, and if the park handle is already set when a // thread tries to wait it will just immediately unpark, see that the signal is still // unset, and park again. Shame about those spent cycles dealing with it though. self.waiting.push(thread::current()); // loop on the park in case we spuriously wake up let mut first = true; while !self.check_signal() { // push every time in case there's a race between `signal` and this, since on // `SignalKind::Auto` it will loop until someone turns it off - but only one will // actually exit this loop, because `check_signal` does a CAS if first { first = false; } else { self.waiting.push(thread::current()); } thread::park(); } } /// Blocks this thread until either another thread calls `signal`, or until the timeout /// elapses. /// /// This function returns the status of the signal when it woke up. If this function exits /// because the signal was set, and this event has a `SignalKind` of `Auto`, the signal will be /// reset so that the next thread to wait will block. pub fn wait_timeout(&self, timeout: Duration) -> bool { use std::time::Instant; // see SignalEvent::wait for why we push first even if the signal is already set self.waiting.push(thread::current()); let begin = Instant::now(); let mut first = true; let mut remaining = timeout; loop { if self.check_signal() { return true; } if first { first = false; } else { let elapsed = begin.elapsed(); if elapsed >= timeout { return self.status(); } else { remaining = timeout - elapsed; } self.waiting.push(thread::current()); } thread::park_timeout(remaining); } } /// Perfoms an atomic compare-exchange on the signal, resetting it if (1) it was set, and (2) /// this `SignalEvent` was configured with `SignalKind::Auto`. Returns whether the signal was /// previously set. fn check_signal(&self) -> bool { self.signal .compare_exchange_weak( true, self.reset == SignalKind::Manual, Ordering::SeqCst, Ordering::SeqCst, ) .unwrap_or_else(identity) } } synchronoise-1.0.1/src/lib.rs000064400000000000000000000020300072674642500142740ustar 00000000000000//! A collection of synchronization primitives that build on the primitives available in the //! standard library. //! //! This library contains the following special-purpose synchronization primitives: //! //! * [`CountdownEvent`], a primitive that keeps a counter and allows a thread to wait until the //! counter reaches zero. //! * [`SignalEvent`], a primitive that allows one or more threads to wait on a signal from another //! thread. //! * [`WriterReaderPhaser`], a primitive that allows multiple wait-free "writer critical sections" //! against a "reader phase flip" that waits for currently-active writers to finish. //! //! [`CountdownEvent`]: struct.CountdownEvent.html //! [`SignalEvent`]: struct.SignalEvent.html //! [`WriterReaderPhaser`]: struct.WriterReaderPhaser.html #![deny(warnings, missing_docs)] // Name source: http://bulbapedia.bulbagarden.net/wiki/Synchronoise_(move) extern crate crossbeam_queue; pub mod event; pub mod phaser; pub use event::{CountdownEvent, SignalEvent}; pub use phaser::WriterReaderPhaser; synchronoise-1.0.1/src/phaser.rs000064400000000000000000000172130072674642500150210ustar 00000000000000//! Support module for `WriterReaderPhaser` and related structs. //! //! See the documentation of the [`WriterReaderPhaser`] struct for more information. //! //! [`WriterReaderPhaser`]: struct.WriterReaderPhaser.html use std::sync::{Arc, Mutex, LockResult, MutexGuard}; use std::sync::atomic::{AtomicIsize, Ordering}; use std::isize::MIN as ISIZE_MIN; use std::time::Duration; use std::thread; /// A synchronization primitive that allows for multiple concurrent wait-free "writer critical /// sections" and a "reader phase flip" that can wait for all currently-active writers to finish. /// /// The basic interaction setup for a `WriterReaderPhaser` is as follows: /// /// * Any number of writers can open and close a "writer critical section" with no waiting. /// * Zero or one readers can be active at one time, by holding a "read lock". Any reader who /// wishes to open a "read lock" while another one is active is blocked until the previous one /// finishes. /// * The holder of a read lock may request a "phase flip", which causes the reader to wait until /// all current writer critical sections are finished before continuing. /// /// `WriterReaderPhaser` is a port of the primitive of the same name from `HdrHistogram`. For a /// summary of the rationale behind its design, see [this post by its author][wrp-blog]. Part of /// its assumptions is that this primitive is synchronizing access to a double-buffered set of /// counters, and the readers are expected to swap the buffers while holding a read lock but before /// flipping the phase. This allows them to access a stable sample to read and perform calculations /// from, while writers still have wait-free synchronization. /// /// [wrp-blog]: https://stuff-gil-says.blogspot.com/2014/11/writerreaderphaser-story-about-new.html /// /// "Writer critical sections" and "read locks" are represented by guard structs that allow /// scope-based resource management of the counters and locks. /// /// * The `PhaserCriticalSection` atomically increments and decrements the phase counters upon /// creation and drop. These operations use `std::sync::atomic::AtomicIsize` from the standard /// library, and provide no-wait handling for platforms with atomic addition instructions. /// * The `PhaserReadLock` is kept in the `WriterReaderPhaser` as a Mutex, enforcing the mutual /// exclusion of the read lock. The "phase flip" operation is defined on the read lock guard /// itself, enforcing that only the holder of a read lock can execute one. pub struct WriterReaderPhaser { start_epoch: Arc, even_end_epoch: Arc, odd_end_epoch: Arc, read_lock: Mutex, } /// Guard struct that represents a "writer critical section" for a `WriterReaderPhaser`. /// /// `PhaserCriticalSection` is a scope-based guard to signal the beginning and end of a "writer /// critical section" to the phaser. Upon calling `writer_critical_section`, the phaser atomically /// increments a counter, and when the returned `PhaserCriticalSection` drops, the `drop` call /// atomically increments another counter. On platforms with atomic increment instructions, this /// should result in wait-free synchronization. /// /// # Example /// /// ``` /// # let phaser = synchronoise::WriterReaderPhaser::new(); /// { /// let _guard = phaser.writer_critical_section(); /// // perform writes /// } // _guard drops, signaling the end of the section /// ``` pub struct PhaserCriticalSection { end_epoch: Arc, } /// Upon drop, a `PhaserCriticalSection` will signal its parent `WriterReaderPhaser` that the /// critical section has ended. impl Drop for PhaserCriticalSection { fn drop(&mut self) { self.end_epoch.fetch_add(1, Ordering::Release); } } /// Guard struct for a `WriterReaderPhaser` that allows a reader to perform a "phase flip". /// /// The `PhaserReadLock` struct allows one to perform a "phase flip" on its parent /// `WriterReaderPhaser`. It is held in a `std::sync::Mutex` in its parent phaser, enforcing that /// only one reader may be active at once. /// /// The `flip_phase` call performs a spin-wait while waiting the the currently-active writers to /// finish. A sleep time may be added between checks by calling `flip_with_sleep` instead. /// /// # Example /// /// ``` /// # let phaser = synchronoise::WriterReaderPhaser::new(); /// { /// let lock = phaser.read_lock().unwrap(); /// // swap buffers /// lock.flip_phase(); /// // reader now has access to a stable snapshot /// } // lock drops, relinquishing the read lock and allowing another reader to lock /// ``` pub struct PhaserReadLock { start_epoch: Arc, even_end_epoch: Arc, odd_end_epoch: Arc, } impl WriterReaderPhaser { /// Creates a new `WriterReaderPhaser`. pub fn new() -> WriterReaderPhaser { let start = Arc::new(AtomicIsize::new(0)); let even = Arc::new(AtomicIsize::new(0)); let odd = Arc::new(AtomicIsize::new(ISIZE_MIN)); let read_lock = PhaserReadLock { start_epoch: start.clone(), even_end_epoch: even.clone(), odd_end_epoch: odd.clone(), }; WriterReaderPhaser { start_epoch: start, even_end_epoch: even, odd_end_epoch: odd, read_lock: Mutex::new(read_lock), } } /// Enters a writer critical section, returning a guard object that signals the end of the /// critical section upon drop. pub fn writer_critical_section(&self) -> PhaserCriticalSection { let flag = self.start_epoch.fetch_add(1, Ordering::Release); if flag < 0 { PhaserCriticalSection { end_epoch: self.odd_end_epoch.clone(), } } else { PhaserCriticalSection { end_epoch: self.even_end_epoch.clone(), } } } /// Enter a reader criticial section, potentially blocking until a currently active read /// section finishes. Returns a guard object that allows the user to flip the phase of the /// `WriterReaderPhaser`, and unlocks the read lock upon drop. /// /// # Errors /// /// If another reader critical section panicked while holding the read lock, this call will /// return an error once the lock is acquired. See the documentation for /// `std::sync::Mutex::lock` for details. pub fn read_lock(&self) -> LockResult> { self.read_lock.lock() } } impl PhaserReadLock { /// Wait until all currently-active writer critical sections have completed. pub fn flip_phase(&self) { self.flip_with_sleep(Duration::default()); } /// Wait until all currently-active writer critical sections have completed. While waiting, /// sleep with the given duration. pub fn flip_with_sleep(&self, sleep_time: Duration) { let next_phase_even = self.start_epoch.load(Ordering::Relaxed) < 0; let start_value = if next_phase_even { let tmp = 0; self.even_end_epoch.store(tmp, Ordering::Relaxed); tmp } else { let tmp = ISIZE_MIN; self.odd_end_epoch.store(tmp, Ordering::Relaxed); tmp }; let value_at_flip = self.start_epoch.swap(start_value, Ordering::AcqRel); let end_epoch = if next_phase_even { self.odd_end_epoch.clone() } else { self.even_end_epoch.clone() }; while end_epoch.load(Ordering::Relaxed) != value_at_flip { if sleep_time == Duration::default() { thread::yield_now(); } else { thread::sleep(sleep_time); } } } }