crossbeam-0.3.2/.gitignore010066400017510001751000000001561322354373700137220ustar0000000000000000# Compiled files *.o *.so *.rlib *.dll *.class # Executables *.exe # Generated by Cargo /target/ Cargo.lock crossbeam-0.3.2/.travis.yml010066400017510001751000000014141322354373700140410ustar0000000000000000language: rust # necessary for `travis-cargo coveralls --no-sudo` addons: apt: packages: - libcurl4-openssl-dev - libelf-dev - libdw-dev # run builds for all the trains (and more) rust: - nightly - beta - stable # load travis-cargo before_script: - | pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH # the main build script: - | travis-cargo build && travis-cargo test && travis-cargo test -- --release && travis-cargo run -- --bin bench --release && travis-cargo --only stable doc env: global: # override the default `--features unstable` used for the nightly branch (optional) - TRAVIS_CARGO_NIGHTLY_FEATURE=nightly notifications: email: on_success: never crossbeam-0.3.2/CHANGELOG.md010066400017510001751000000013641322354550400135370ustar0000000000000000# Version 0.3 - Introduced `ScopedThreadBuilder` with the ability to name threads and set stack size - `Worker` methods in the Chase-Lev deque don't require mutable access anymore - Fixed a bug when unblocking `pop()` in `MsQueue` - Implemented `Drop` for `MsQueue`, `SegQueue`, and `TreiberStack` - Implemented `Default` for `TreiberStack` - Added `is_empty` to `SegQueue` - Renamed `mem::epoch` to `epoch` - Other bug fixes # Version 0.2 - Changed existing non-blocking `pop` methods to `try_pop` - Added blocking `pop` support to Michael-Scott queue - Added Chase-Lev work-stealing deque # Version 0.1 - Added [epoch-based memory management](http://aturon.github.io/blog/2015/08/27/epoch/) - Added Michael-Scott queue - Added Segmented array queue crossbeam-0.3.2/Cargo.toml.orig010066400017510001751000000006741322366445500146270ustar0000000000000000[package] name = "crossbeam" version = "0.3.2" authors = ["Aaron Turon "] description = "Support for lock-free data structures, synchronizers, and parallel programming" repository = "https://github.com/crossbeam-rs/crossbeam" documentation = "https://docs.rs/crossbeam" readme = "README.md" license = "Apache-2.0/MIT" categories = ["concurrency", "data-structures"] [features] nightly = [] [dev-dependencies] rand = "0.3" crossbeam-0.3.2/Cargo.toml0000644000000017170000000000000110570ustar00# 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 = "crossbeam" version = "0.3.2" authors = ["Aaron Turon "] description = "Support for lock-free data structures, synchronizers, and parallel programming" documentation = "https://docs.rs/crossbeam" readme = "README.md" categories = ["concurrency", "data-structures"] license = "Apache-2.0/MIT" repository = "https://github.com/crossbeam-rs/crossbeam" [dev-dependencies.rand] version = "0.3" [features] nightly = [] crossbeam-0.3.2/LICENSE-APACHE010066400017510001751000000251371322354373700136640ustar0000000000000000 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. crossbeam-0.3.2/LICENSE-MIT010066400017510001751000000020571322354373700133700ustar0000000000000000Copyright (c) 2015 The Rust Project 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. crossbeam-0.3.2/README.md010066400017510001751000000033621322354550400132050ustar0000000000000000# Notice This crate is outdated. The Crossbeam project is currently in a transition period. We are rewriting the epoch garbage collector, as well as several other utilities and adding new structures. To follow the progress, please take a look at other crates in the project [here](https://github.com/crossbeam-rs). When the transition is complete, this crate will be updated to use the new code. # Crossbeam: support for concurrent and parallel programming [![Build Status](https://travis-ci.org/crossbeam-rs/crossbeam.svg?branch=master)](https://travis-ci.org/crossbeam-rs/crossbeam) This crate is an early work in progress. The focus for the moment is concurrency: - **Non-blocking data structures**. These data structures allow for high performance, highly-concurrent access, much superior to wrapping with a `Mutex`. Ultimately the goal is to include stacks, queues, deques, bags, sets and maps. - **Memory management**. Because non-blocking data structures avoid global synchronization, it is not easy to tell when internal data can be safely freed. The `epoch` module provides generic, easy to use, and high-performance APIs for managing memory in these cases. - **Synchronization**. The standard library provides a few synchronization primitives (locks, barriers, etc) but this crate seeks to expand that set to include more advanced/niche primitives, as well as userspace alternatives. - **Scoped thread API**. Finally, the crate provides a "scoped" thread API, making it possible to spawn threads that share stack data with their parents. # Usage To use Crossbeam, add this to your `Cargo.toml`: ```toml [dependencies] crossbeam = "0.3.0" ``` For examples of what Crossbeam is capable of, see the [documentation][docs]. [docs]: https://docs.rs/crossbeam/ crossbeam-0.3.2/src/bin/bench.rs010066400017510001751000000077611322354550400147210ustar0000000000000000extern crate crossbeam; use std::collections::VecDeque; use std::sync::Mutex; use std::sync::mpsc::channel; use std::time::Duration; use crossbeam::scope; use crossbeam::sync::MsQueue; use crossbeam::sync::SegQueue; use extra_impls::mpsc_queue::Queue as MpscQueue; mod extra_impls; const COUNT: u64 = 10000000; const THREADS: u64 = 2; fn time(f: F) -> Duration { let start = ::std::time::Instant::now(); f(); start.elapsed() } fn nanos(d: Duration) -> f64 { d.as_secs() as f64 * 1000000000f64 + (d.subsec_nanos() as f64) } trait Queue { fn push(&self, T); fn try_pop(&self) -> Option; } impl Queue for MsQueue { fn push(&self, t: T) { self.push(t) } fn try_pop(&self) -> Option { self.try_pop() } } impl Queue for SegQueue { fn push(&self, t: T) { self.push(t) } fn try_pop(&self) -> Option { self.try_pop() } } impl Queue for MpscQueue { fn push(&self, t: T) { self.push(t) } fn try_pop(&self) -> Option { use extra_impls::mpsc_queue::*; loop { match self.pop() { Data(t) => return Some(t), Empty => return None, Inconsistent => (), } } } } impl Queue for Mutex> { fn push(&self, t: T) { self.lock().unwrap().push_back(t) } fn try_pop(&self) -> Option { self.lock().unwrap().pop_front() } } fn bench_queue_mpsc + Sync>(q: Q) -> f64 { let d = time(|| { scope(|scope| { for _i in 0..THREADS { let qr = &q; scope.spawn(move || { for x in 0..COUNT { let _ = qr.push(x); } }); } let mut count = 0; while count < COUNT*THREADS { if q.try_pop().is_some() { count += 1; } } }); }); nanos(d) / ((COUNT * THREADS) as f64) } fn bench_queue_mpmc + Sync>(q: Q) -> f64 { use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::Relaxed; let prod_count = AtomicUsize::new(0); let d = time(|| { scope(|scope| { for _i in 0..THREADS { let qr = &q; let pcr = &prod_count; scope.spawn(move || { for _x in 0..COUNT { qr.push(true); } if pcr.fetch_add(1, Relaxed) == (THREADS as usize) - 1 { for _x in 0..THREADS { qr.push(false) } } }); scope.spawn(move || { loop { if let Some(false) = qr.try_pop() { break } } }); } }); }); nanos(d) / ((COUNT * THREADS) as f64) } fn bench_chan_mpsc() -> f64 { let (tx, rx) = channel(); let d = time(|| { scope(|scope| { for _i in 0..THREADS { let my_tx = tx.clone(); scope.spawn(move || { for x in 0..COUNT { let _ = my_tx.send(x); } }); } for _i in 0..COUNT*THREADS { let _ = rx.recv().unwrap(); } }); }); nanos(d) / ((COUNT * THREADS) as f64) } fn main() { println!("MSQ mpsc: {}", bench_queue_mpsc(MsQueue::new())); println!("chan mpsc: {}", bench_chan_mpsc()); println!("mpsc mpsc: {}", bench_queue_mpsc(MpscQueue::new())); println!("Seg mpsc: {}", bench_queue_mpsc(SegQueue::new())); println!("MSQ mpmc: {}", bench_queue_mpmc(MsQueue::new())); println!("Seg mpmc: {}", bench_queue_mpmc(SegQueue::new())); // println!("queue_mpsc: {}", bench_queue_mpsc()); // println!("queue_mpmc: {}", bench_queue_mpmc()); // println!("mutex_mpmc: {}", bench_mutex_mpmc()); } crossbeam-0.3.2/src/bin/extra_impls/mod.rs010066400017510001751000000000241322354373700167370ustar0000000000000000pub mod mpsc_queue; crossbeam-0.3.2/src/bin/extra_impls/mpsc_queue.rs010066400017510001751000000130241322354373700203320ustar0000000000000000/* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of Dmitry Vyukov. */ //! A mostly lock-free multi-producer, single consumer queue. //! //! This module contains an implementation of a concurrent MPSC queue. This //! queue can be used to share data between threads, and is also used as the //! building block of channels in rust. //! //! Note that the current implementation of this queue has a caveat of the `pop` //! method, and see the method for more information about it. Due to this //! caveat, this queue may not be appropriate for all use-cases. // http://www.1024cores.net/home/lock-free-algorithms // /queues/non-intrusive-mpsc-node-based-queue pub use self::PopResult::*; use std::fmt; use std::ptr; use std::cell::UnsafeCell; use std::sync::atomic::{AtomicPtr, Ordering}; /// A result of the `pop` function. #[derive(Debug)] pub enum PopResult { /// Some data has been popped Data(T), /// The queue is empty Empty, /// The queue is in an inconsistent state. Popping data should succeed, but /// some pushers have yet to make enough progress in order allow a pop to /// succeed. It is recommended that a pop() occur "in the near future" in /// order to see if the sender has made progress or not Inconsistent, } #[derive(Debug)] struct Node { next: AtomicPtr>, value: Option, } /// The multi-producer single-consumer structure. This is not cloneable, but it /// may be safely shared so long as it is guaranteed that there is only one /// popper at a time (many pushers are allowed). pub struct Queue { head: AtomicPtr>, tail: UnsafeCell<*mut Node>, } impl fmt::Debug for Queue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Queue {{ ... }}") } } unsafe impl Send for Queue { } unsafe impl Sync for Queue { } impl Node { unsafe fn new(v: Option) -> *mut Node { Box::into_raw(Box::new(Node { next: AtomicPtr::new(ptr::null_mut()), value: v, })) } } impl Queue { /// Creates a new queue that is safe to share among multiple producers and /// one consumer. pub fn new() -> Queue { let stub = unsafe { Node::new(None) }; Queue { head: AtomicPtr::new(stub), tail: UnsafeCell::new(stub), } } /// Pushes a new value onto this queue. pub fn push(&self, t: T) { unsafe { let n = Node::new(Some(t)); let prev = self.head.swap(n, Ordering::AcqRel); (*prev).next.store(n, Ordering::Release); } } /// Pops some data from this queue. /// /// Note that the current implementation means that this function cannot /// return `Option`. It is possible for this queue to be in an /// inconsistent state where many pushes have succeeded and completely /// finished, but pops cannot return `Some(t)`. This inconsistent state /// happens when a pusher is pre-empted at an inopportune moment. /// /// This inconsistent state means that this queue does indeed have data, but /// it does not currently have access to it at this time. pub fn pop(&self) -> PopResult { unsafe { let tail = *self.tail.get(); let next = (*tail).next.load(Ordering::Acquire); if !next.is_null() { *self.tail.get() = next; assert!((*tail).value.is_none()); assert!((*next).value.is_some()); let ret = (*next).value.take().unwrap(); let _ = Box::from_raw(tail); return Data(ret); } if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent} } } } impl Drop for Queue { fn drop(&mut self) { unsafe { let mut cur = *self.tail.get(); while !cur.is_null() { let next = (*cur).next.load(Ordering::Relaxed); let _ = Box::from_raw(cur); cur = next; } } } } crossbeam-0.3.2/src/bin/stress-msq.rs010066400017510001751000000015061322354373700157600ustar0000000000000000extern crate crossbeam; use crossbeam::sync::MsQueue; use crossbeam::scope; use std::sync::Arc; const DUP: usize = 4; const THREADS: u32 = 2; const COUNT: u64 = 100000; fn main() { scope(|s| { for _i in 0..DUP { let q = Arc::new(MsQueue::new()); let qs = q.clone(); s.spawn(move || { for i in 1..COUNT { qs.push(i) } }); for _i in 0..THREADS { let qr = q.clone(); s.spawn(move || { let mut cur: u64 = 0; for _j in 0..COUNT { if let Some(new) = qr.try_pop() { assert!(new > cur); cur = new; } } }); } } }); } crossbeam-0.3.2/src/cache_padded.rs010066400017510001751000000106451322366442700154370ustar0000000000000000use std::marker; use std::cell::UnsafeCell; use std::fmt; use std::mem; use std::ptr; use std::ops::{Deref, DerefMut}; // For now, treat this as an arch-independent constant. const CACHE_LINE: usize = 32; #[cfg_attr(feature = "nightly", repr(simd))] #[derive(Debug)] struct Padding(u64, u64, u64, u64); /// Pad `T` to the length of a cacheline. /// /// Sometimes concurrent programming requires a piece of data to be padded out /// to the size of a cacheline to avoid "false sharing": cachelines being /// invalidated due to unrelated concurrent activity. Use the `CachePadded` type /// when you want to *avoid* cache locality. /// /// At the moment, cache lines are assumed to be 32 * sizeof(usize) on all /// architectures. /// /// **Warning**: the wrapped data is never dropped; move out using `ptr::read` /// if you need to run dtors. pub struct CachePadded { data: UnsafeCell<[usize; CACHE_LINE]>, _marker: ([Padding; 0], marker::PhantomData), } impl fmt::Debug for CachePadded { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CachePadded {{ ... }}") } } unsafe impl Send for CachePadded {} unsafe impl Sync for CachePadded {} #[cfg(not(feature = "nightly"))] macro_rules! declare_zeros_valid { () => { /// Types for which mem::zeroed() is safe. /// /// If a type `T: ZerosValid`, then a sequence of zeros the size of `T` must be /// a valid member of the type `T`. pub unsafe trait ZerosValid {} } } #[cfg(feature = "nightly")] macro_rules! declare_zeros_valid { () => { /// Types for which mem::zeroed() is safe. /// /// If a type `T: ZerosValid`, then a sequence of zeros the size of `T` must be /// a valid member of the type `T`. pub unsafe auto trait ZerosValid {} } } declare_zeros_valid!(); macro_rules! zeros_valid { ($( $T:ty )*) => ($( unsafe impl ZerosValid for $T {} )*)} zeros_valid!(u8 u16 u32 u64 usize); zeros_valid!(i8 i16 i32 i64 isize); unsafe impl ZerosValid for ::std::sync::atomic::AtomicUsize {} unsafe impl ZerosValid for ::std::sync::atomic::AtomicPtr {} impl CachePadded { /// A const fn equivalent to mem::zeroed(). #[cfg(not(feature = "nightly"))] pub fn zeroed() -> CachePadded { CachePadded { data: UnsafeCell::new(([0; CACHE_LINE])), _marker: ([], marker::PhantomData), } } /// A const fn equivalent to mem::zeroed(). #[cfg(feature = "nightly")] pub const fn zeroed() -> CachePadded { CachePadded { data: UnsafeCell::new(([0; CACHE_LINE])), _marker: ([], marker::PhantomData), } } } #[inline] /// Assert that the size and alignment of `T` are consistent with `CachePadded`. fn assert_valid() { assert!(mem::size_of::() <= mem::size_of::>()); assert!(mem::align_of::() <= mem::align_of::>()); } impl CachePadded { /// Wrap `t` with cacheline padding. /// /// **Warning**: the wrapped data is never dropped; move out using /// `ptr:read` if you need to run dtors. pub fn new(t: T) -> CachePadded { assert_valid::(); let ret = CachePadded { data: UnsafeCell::new(([0; CACHE_LINE])), _marker: ([], marker::PhantomData), }; unsafe { let p: *mut T = mem::transmute(&ret.data); ptr::write(p, t); } ret } } impl Deref for CachePadded { type Target = T; fn deref(&self) -> &T { assert_valid::(); unsafe { mem::transmute(&self.data) } } } impl DerefMut for CachePadded { fn deref_mut(&mut self) -> &mut T { assert_valid::(); unsafe { mem::transmute(&mut self.data) } } } // FIXME: support Drop by pulling out a version usable for statics /* impl Drop for CachePadded { fn drop(&mut self) { assert_valid::(); let p: *mut T = mem::transmute(&self.data); mem::drop(ptr::read(p)); } } */ #[cfg(test)] mod test { use super::*; #[test] fn cache_padded_store_u64() { let x: CachePadded = CachePadded::new(17); assert_eq!(*x, 17); } #[test] fn cache_padded_store_pair() { let x: CachePadded<(u64, u64)> = CachePadded::new((17, 37)); assert_eq!(x.0, 17); assert_eq!(x.1, 37); } } crossbeam-0.3.2/src/epoch/atomic.rs010066400017510001751000000144151322354550400154360ustar0000000000000000use std::marker::PhantomData; use std::mem; use std::ptr; use std::sync::atomic::{self, Ordering}; use super::{Owned, Shared, Guard}; /// Like `std::sync::atomic::AtomicPtr`. /// /// Provides atomic access to a (nullable) pointer of type `T`, interfacing with /// the `Owned` and `Shared` types. #[derive(Debug)] pub struct Atomic { ptr: atomic::AtomicPtr, _marker: PhantomData<*const ()>, } unsafe impl Send for Atomic {} unsafe impl Sync for Atomic {} fn opt_shared_into_raw(val: Option>) -> *mut T { val.map(|p| p.as_raw()).unwrap_or(ptr::null_mut()) } fn opt_owned_as_raw(val: &Option>) -> *mut T { val.as_ref().map(Owned::as_raw).unwrap_or(ptr::null_mut()) } fn opt_owned_into_raw(val: Option>) -> *mut T { let ptr = val.as_ref().map(Owned::as_raw).unwrap_or(ptr::null_mut()); mem::forget(val); ptr } impl Atomic { /// Create a new, null atomic pointer. #[cfg(feature = "nightly")] pub const fn null() -> Atomic { Atomic { ptr: atomic::AtomicPtr::new(0 as *mut _), _marker: PhantomData } } #[cfg(not(feature = "nightly"))] pub fn null() -> Atomic { Atomic { ptr: atomic::AtomicPtr::new(0 as *mut _), _marker: PhantomData } } /// Create a new atomic pointer pub fn new(data: T) -> Atomic { Atomic { ptr: atomic::AtomicPtr::new(Box::into_raw(Box::new(data))), _marker: PhantomData } } /// Do an atomic load with the given memory ordering. /// /// In order to perform the load, we must pass in a borrow of a /// `Guard`. This is a way of guaranteeing that the thread has pinned the /// epoch for the entire lifetime `'a`. In return, you get an optional /// `Shared` pointer back (`None` if the `Atomic` is currently null), with /// lifetime tied to the guard. /// /// # Panics /// /// Panics if `ord` is `Release` or `AcqRel`. pub fn load<'a>(&self, ord: Ordering, _: &'a Guard) -> Option> { unsafe { Shared::from_raw(self.ptr.load(ord)) } } /// Do an atomic store with the given memory ordering. /// /// Transfers ownership of the given `Owned` pointer, if any. Since no /// lifetime information is acquired, no `Guard` value is needed. /// /// # Panics /// /// Panics if `ord` is `Acquire` or `AcqRel`. pub fn store(&self, val: Option>, ord: Ordering) { self.ptr.store(opt_owned_into_raw(val), ord) } /// Do an atomic store with the given memory ordering, immediately yielding /// a shared reference to the pointer that was stored. /// /// Transfers ownership of the given `Owned` pointer, yielding a `Shared` /// reference to it. Since the reference is valid only for the curent epoch, /// it's lifetime is tied to a `Guard` value. /// /// # Panics /// /// Panics if `ord` is `Acquire` or `AcqRel`. pub fn store_and_ref<'a>(&self, val: Owned, ord: Ordering, _: &'a Guard) -> Shared<'a, T> { unsafe { let shared = Shared::from_owned(val); self.store_shared(Some(shared), ord); shared } } /// Do an atomic store of a `Shared` pointer with the given memory ordering. /// /// This operation does not require a guard, because it does not yield any /// new information about the lifetime of a pointer. /// /// # Panics /// /// Panics if `ord` is `Acquire` or `AcqRel`. pub fn store_shared(&self, val: Option>, ord: Ordering) { self.ptr.store(opt_shared_into_raw(val), ord) } /// Do a compare-and-set from a `Shared` to an `Owned` pointer with the /// given memory ordering. /// /// As with `store`, this operation does not require a guard; it produces no new /// lifetime information. The `Result` indicates whether the CAS succeeded; if /// not, ownership of the `new` pointer is returned to the caller. pub fn cas(&self, old: Option>, new: Option>, ord: Ordering) -> Result<(), Option>> { if self.ptr.compare_and_swap(opt_shared_into_raw(old), opt_owned_as_raw(&new), ord) == opt_shared_into_raw(old) { mem::forget(new); Ok(()) } else { Err(new) } } /// Do a compare-and-set from a `Shared` to an `Owned` pointer with the /// given memory ordering, immediatley acquiring a new `Shared` reference to /// the previously-owned pointer if successful. /// /// This operation is analogous to `store_and_ref`. pub fn cas_and_ref<'a>(&self, old: Option>, new: Owned, ord: Ordering, _: &'a Guard) -> Result, Owned> { if self.ptr.compare_and_swap(opt_shared_into_raw(old), new.as_raw(), ord) == opt_shared_into_raw(old) { Ok(unsafe { Shared::from_owned(new) }) } else { Err(new) } } /// Do a compare-and-set from a `Shared` to another `Shared` pointer with /// the given memory ordering. /// /// The boolean return value is `true` when the CAS is successful. pub fn cas_shared(&self, old: Option>, new: Option>, ord: Ordering) -> bool { self.ptr.compare_and_swap(opt_shared_into_raw(old), opt_shared_into_raw(new), ord) == opt_shared_into_raw(old) } /// Do an atomic swap with an `Owned` pointer with the given memory ordering. pub fn swap<'a>(&self, new: Option>, ord: Ordering, _: &'a Guard) -> Option> { unsafe { Shared::from_raw(self.ptr.swap(opt_owned_into_raw(new), ord)) } } /// Do an atomic swap with a `Shared` pointer with the given memory ordering. pub fn swap_shared<'a>(&self, new: Option>, ord: Ordering, _: &'a Guard) -> Option> { unsafe { Shared::from_raw(self.ptr.swap(opt_shared_into_raw(new), ord)) } } } crossbeam-0.3.2/src/epoch/garbage.rs010066400017510001751000000070621322354550400155520ustar0000000000000000// Data structures for storing garbage to be freed later (once the // epochs have sufficiently advanced). // // In general, we try to manage the garbage thread locally whenever // possible. Each thread keep track of three bags of garbage. But if a // thread is exiting, these bags must be moved into the global garbage // bags. use std::ptr; use std::mem; use std::sync::atomic::AtomicPtr; use std::sync::atomic::Ordering::{Relaxed, Release, Acquire}; use ZerosValid; /// One item of garbage. /// /// Stores enough information to do a deallocation. #[derive(Debug)] struct Item { ptr: *mut u8, free: unsafe fn(*mut u8), } /// A single, thread-local bag of garbage. #[derive(Debug)] pub struct Bag(Vec); impl Bag { fn new() -> Bag { Bag(vec![]) } fn insert(&mut self, elem: *mut T) { let size = mem::size_of::(); if size > 0 { self.0.push(Item { ptr: elem as *mut u8, free: free::, }) } unsafe fn free(t: *mut u8) { drop(Vec::from_raw_parts(t as *mut T, 0, 1)); } } fn len(&self) -> usize { self.0.len() } /// Deallocate all garbage in the bag pub unsafe fn collect(&mut self) { let mut data = mem::replace(&mut self.0, Vec::new()); for item in data.iter() { (item.free)(item.ptr); } data.truncate(0); self.0 = data; } } // needed because the bags store raw pointers. unsafe impl Send for Bag {} unsafe impl Sync for Bag {} /// A thread-local set of garbage bags. #[derive(Debug)] pub struct Local { /// Garbage added at least one epoch behind the current local epoch pub old: Bag, /// Garbage added in the current local epoch or earlier pub cur: Bag, /// Garbage added in the current *global* epoch pub new: Bag, } impl Local { pub fn new() -> Local { Local { old: Bag::new(), cur: Bag::new(), new: Bag::new(), } } pub fn insert(&mut self, elem: *mut T) { self.new.insert(elem) } /// Collect one epoch of garbage, rotating the local garbage bags. pub unsafe fn collect(&mut self) { let ret = self.old.collect(); mem::swap(&mut self.old, &mut self.cur); mem::swap(&mut self.cur, &mut self.new); ret } pub fn size(&self) -> usize { self.old.len() + self.cur.len() + self.new.len() } } /// A concurrent garbage bag, currently based on Treiber's stack. /// /// The elements are themselves owned `Bag`s. #[derive(Debug)] pub struct ConcBag { head: AtomicPtr, } unsafe impl ZerosValid for ConcBag {} #[derive(Debug)] struct Node { data: Bag, next: AtomicPtr, } impl ConcBag { pub fn insert(&self, t: Bag){ let n = Box::into_raw(Box::new( Node { data: t, next: AtomicPtr::new(ptr::null_mut()) })); loop { let head = self.head.load(Acquire); unsafe { (*n).next.store(head, Relaxed) }; if self.head.compare_and_swap(head, n, Release) == head { break } } } pub unsafe fn collect(&self) { // check to avoid xchg instruction // when no garbage exists let mut head = self.head.load(Relaxed); if head != ptr::null_mut() { head = self.head.swap(ptr::null_mut(), Acquire); while head != ptr::null_mut() { let mut n = Box::from_raw(head); n.data.collect(); head = n.next.load(Relaxed); } } } } crossbeam-0.3.2/src/epoch/global.rs010066400017510001751000000047161322354550400154250ustar0000000000000000// Definition of global epoch state. The `get` function is the way to // access this data externally (until const fn is stabilized...). use std::sync::atomic::AtomicUsize; use CachePadded; use epoch::garbage; use epoch::participants::Participants; /// Global epoch state #[derive(Debug)] pub struct EpochState { /// Current global epoch pub epoch: CachePadded, // FIXME: move this into the `garbage` module, rationalize API /// Global garbage bags pub garbage: [CachePadded; 3], /// Participant list pub participants: Participants, } unsafe impl Send for EpochState {} unsafe impl Sync for EpochState {} pub use self::imp::get; #[cfg(not(feature = "nightly"))] mod imp { use std::mem; use std::sync::atomic::{self, AtomicUsize}; use std::sync::atomic::Ordering::Relaxed; use super::EpochState; use CachePadded; use epoch::participants::Participants; impl EpochState { fn new() -> EpochState { EpochState { epoch: CachePadded::zeroed(), garbage: [CachePadded::zeroed(), CachePadded::zeroed(), CachePadded::zeroed()], participants: Participants::new(), } } } static EPOCH: AtomicUsize = atomic::ATOMIC_USIZE_INIT; pub fn get() -> &'static EpochState { let mut addr = EPOCH.load(Relaxed); if addr == 0 { let boxed = Box::new(EpochState::new()); let raw = Box::into_raw(boxed); addr = EPOCH.compare_and_swap(0, raw as usize, Relaxed); if addr != 0 { let boxed = unsafe { Box::from_raw(raw) }; mem::drop(boxed); } else { addr = raw as usize; } } unsafe { &*(addr as *mut EpochState) } } } #[cfg(feature = "nightly")] mod imp { use super::EpochState; use CachePadded; use epoch::participants::Participants; impl EpochState { const fn new() -> EpochState { EpochState { epoch: CachePadded::zeroed(), garbage: [CachePadded::zeroed(), CachePadded::zeroed(), CachePadded::zeroed()], participants: Participants::new(), } } } static EPOCH: EpochState = EpochState::new(); pub fn get() -> &'static EpochState { &EPOCH } } crossbeam-0.3.2/src/epoch/guard.rs010066400017510001751000000031241322354550400152570ustar0000000000000000use std::marker; use super::{local, Shared}; /// An RAII-style guard for pinning the current epoch. /// /// A guard must be acquired before most operations on an `Atomic` pointer. On /// destruction, it unpins the epoch. #[must_use] #[derive(Debug)] pub struct Guard { _marker: marker::PhantomData<*mut ()>, // !Send and !Sync } /// Pin the current epoch. /// /// Threads generally pin before interacting with a lock-free data /// structure. Pinning requires a full memory barrier, so is somewhat /// expensive. It is rentrant -- you can safely acquire nested guards, and only /// the first guard requires a barrier. Thus, in cases where you expect to /// perform several lock-free operations in quick succession, you may consider /// pinning around the entire set of operations. pub fn pin() -> Guard { local::with_participant(|p| { let entered = p.enter(); let g = Guard { _marker: marker::PhantomData, }; if entered && p.should_gc() { p.try_collect(&g); } g }) } impl Guard { /// Assert that the value is no longer reachable from a lock-free data /// structure and should be collected when sufficient epochs have passed. pub unsafe fn unlinked(&self, val: Shared) { local::with_participant(|p| p.reclaim(val.as_raw())) } /// Move the thread-local garbage into the global set of garbage. pub fn migrate_garbage(&self) { local::with_participant(|p| p.migrate_garbage()) } } impl Drop for Guard { fn drop(&mut self) { local::with_participant(|p| p.exit()); } } crossbeam-0.3.2/src/epoch/local.rs010066400017510001751000000016031322354550400152470ustar0000000000000000// Manage the thread-local state, providing access to a `Participant` record. use std::sync::atomic::Ordering::Relaxed; use epoch::participant::Participant; use epoch::global; #[derive(Debug)] struct LocalEpoch { participant: *const Participant, } impl LocalEpoch { fn new() -> LocalEpoch { LocalEpoch { participant: global::get().participants.enroll() } } fn get(&self) -> &Participant { unsafe { &*self.participant } } } // FIXME: avoid leaking when all threads have exited impl Drop for LocalEpoch { fn drop(&mut self) { let p = self.get(); p.enter(); p.migrate_garbage(); p.exit(); p.active.store(false, Relaxed); } } thread_local!(static LOCAL_EPOCH: LocalEpoch = LocalEpoch::new() ); pub fn with_participant(f: F) -> T where F: FnOnce(&Participant) -> T { LOCAL_EPOCH.with(|e| f(e.get())) } crossbeam-0.3.2/src/epoch/mod.rs010066400017510001751000000170371322354550400147440ustar0000000000000000//! Epoch-based memory management //! //! This module provides fast, easy to use memory management for lock free data //! structures. It's inspired by [Keir Fraser's *epoch-based //! reclamation*](https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf). //! //! The basic problem this is solving is the fact that when one thread has //! removed a node from a data structure, other threads may still have pointers //! to that node (in the form of snapshots that will be validated through things //! like compare-and-swap), so the memory cannot be immediately freed. Put differently: //! //! 1. There are two sources of reachability at play -- the data structure, and //! the snapshots in threads accessing it. Before we delete a node, we need to know //! that it cannot be reached in either of these ways. //! //! 2. Once a node has been unlinked from the data structure, no *new* snapshots //! reaching it will be created. //! //! Using the epoch scheme is fairly straightforward, and does not require //! understanding any of the implementation details: //! //! - When operating on a shared data structure, a thread must "pin the current //! epoch", which is done by calling `pin()`. This function returns a `Guard` //! which unpins the epoch when destroyed. //! //! - When the thread subsequently reads from a lock-free data structure, the //! pointers it extracts act like references with lifetime tied to the //! `Guard`. This allows threads to safely read from snapshotted data, being //! guaranteed that the data will remain allocated until they exit the epoch. //! //! To put the `Guard` to use, Crossbeam provides a set of three pointer types meant to work together: //! //! - `Owned`, akin to `Box`, which points to uniquely-owned data that has //! not yet been published in a concurrent data structure. //! //! - `Shared<'a, T>`, akin to `&'a T`, which points to shared data that may or may //! not be reachable from a data structure, but it guaranteed not to be freed //! during lifetime `'a`. //! //! - `Atomic`, akin to `std::sync::atomic::AtomicPtr`, which provides atomic //! updates to a pointer using the `Owned` and `Shared` types, and connects them //! to a `Guard`. //! //! Each of these types provides further documentation on usage. //! //! # Example //! //! ``` //! use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; //! use std::ptr; //! //! use crossbeam::epoch::{self, Atomic, Owned}; //! //! struct TreiberStack { //! head: Atomic>, //! } //! //! struct Node { //! data: T, //! next: Atomic>, //! } //! //! impl TreiberStack { //! fn new() -> TreiberStack { //! TreiberStack { //! head: Atomic::null() //! } //! } //! //! fn push(&self, t: T) { //! // allocate the node via Owned //! let mut n = Owned::new(Node { //! data: t, //! next: Atomic::null(), //! }); //! //! // become active //! let guard = epoch::pin(); //! //! loop { //! // snapshot current head //! let head = self.head.load(Relaxed, &guard); //! //! // update `next` pointer with snapshot //! n.next.store_shared(head, Relaxed); //! //! // if snapshot is still good, link in the new node //! match self.head.cas_and_ref(head, n, Release, &guard) { //! Ok(_) => return, //! Err(owned) => n = owned, //! } //! } //! } //! //! fn pop(&self) -> Option { //! // become active //! let guard = epoch::pin(); //! //! loop { //! // take a snapshot //! match self.head.load(Acquire, &guard) { //! // the stack is non-empty //! Some(head) => { //! // read through the snapshot, *safely*! //! let next = head.next.load(Relaxed, &guard); //! //! // if snapshot is still good, update from `head` to `next` //! if self.head.cas_shared(Some(head), next, Release) { //! unsafe { //! // mark the node as unlinked //! guard.unlinked(head); //! //! // extract out the data from the now-unlinked node //! return Some(ptr::read(&(*head).data)) //! } //! } //! } //! //! // we observed the stack empty //! None => return None //! } //! } //! } //! } //! ``` // FIXME: document implementation details mod atomic; mod garbage; mod global; mod guard; mod local; mod participant; mod participants; pub use self::atomic::Atomic; pub use self::guard::{pin, Guard}; use std::ops::{Deref, DerefMut}; use std::ptr; use std::mem; /// Like `Box`: an owned, heap-allocated data value of type `T`. #[derive(Debug)] pub struct Owned { data: Box, } impl Owned { /// Move `t` to a new heap allocation. pub fn new(t: T) -> Owned { Owned { data: Box::new(t) } } fn as_raw(&self) -> *mut T { self.deref() as *const _ as *mut _ } /// Move data out of the owned box, deallocating the box. pub fn into_inner(self) -> T { *self.data } } impl Deref for Owned { type Target = T; fn deref(&self) -> &T { &self.data } } impl DerefMut for Owned { fn deref_mut(&mut self) -> &mut T { &mut self.data } } #[derive(PartialEq, Eq)] /// Like `&'a T`: a shared reference valid for lifetime `'a`. #[derive(Debug)] pub struct Shared<'a, T: 'a> { data: &'a T, } impl<'a, T> Copy for Shared<'a, T> {} impl<'a, T> Clone for Shared<'a, T> { fn clone(&self) -> Shared<'a, T> { Shared { data: self.data } } } impl<'a, T> Deref for Shared<'a, T> { type Target = &'a T; fn deref(&self) -> &&'a T { &self.data } } impl<'a, T> Shared<'a, T> { unsafe fn from_raw(raw: *mut T) -> Option> { if raw == ptr::null_mut() { None } else { Some(Shared { data: mem::transmute::<*mut T, &T>(raw) }) } } unsafe fn from_ref(r: &T) -> Shared<'a, T> { Shared { data: mem::transmute(r) } } unsafe fn from_owned(owned: Owned) -> Shared<'a, T> { let ret = Shared::from_ref(owned.deref()); mem::forget(owned); ret } pub fn as_raw(&self) -> *mut T { self.data as *const _ as *mut _ } } #[cfg(test)] mod test { use std::sync::atomic::Ordering; use super::*; use epoch; #[test] fn test_no_drop() { static mut DROPS: i32 = 0; struct Test; impl Drop for Test { fn drop(&mut self) { unsafe { DROPS += 1; } } } let g = pin(); let x = Atomic::null(); x.store(Some(Owned::new(Test)), Ordering::Relaxed); x.store_and_ref(Owned::new(Test), Ordering::Relaxed, &g); let y = x.load(Ordering::Relaxed, &g); let z = x.cas_and_ref(y, Owned::new(Test), Ordering::Relaxed, &g).ok(); let _ = x.cas(z, Some(Owned::new(Test)), Ordering::Relaxed); x.swap(Some(Owned::new(Test)), Ordering::Relaxed, &g); unsafe { assert_eq!(DROPS, 0); } } #[test] fn test_new() { let guard = epoch::pin(); let my_atomic = Atomic::new(42); assert_eq!(**my_atomic.load(Ordering::Relaxed, &guard).unwrap(), 42); } } crossbeam-0.3.2/src/epoch/participant.rs010066400017510001751000000103641322354550400164770ustar0000000000000000// Manages a single participant in the epoch scheme. This is where all // of the actual epoch management logic happens! use std::mem; use std::cell::UnsafeCell; use std::fmt; use std::sync::atomic::{self, AtomicUsize, AtomicBool}; use std::sync::atomic::Ordering::{Relaxed, Acquire, Release, SeqCst}; use epoch::{Atomic, Guard, garbage, global}; use epoch::participants::ParticipantNode; /// Thread-local data for epoch participation. pub struct Participant { /// The local epoch. epoch: AtomicUsize, /// Number of pending uses of `epoch::pin()`; keeping a count allows for /// reentrant use of epoch management. in_critical: AtomicUsize, /// Thread-local garbage tracking garbage: UnsafeCell, /// Is the thread still active? Becomes `false` when the thread exits. This /// is ultimately used to free `Participant` records. pub active: AtomicBool, /// The participant list is coded intrusively; here's the `next` pointer. pub next: Atomic, } impl fmt::Debug for Participant { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Participant {{ ... }}") } } unsafe impl Sync for Participant {} const GC_THRESH: usize = 32; impl Participant { pub fn new() -> Participant { Participant { epoch: AtomicUsize::new(0), in_critical: AtomicUsize::new(0), active: AtomicBool::new(true), garbage: UnsafeCell::new(garbage::Local::new()), next: Atomic::null(), } } /// Enter a critical section. /// /// This method is reentrant, allowing for nested critical sections. /// /// Returns `true` is this is the first entry on the stack (as opposed to a /// re-entrant call). pub fn enter(&self) -> bool { let new_count = self.in_critical.load(Relaxed) + 1; self.in_critical.store(new_count, Relaxed); if new_count > 1 { return false } atomic::fence(SeqCst); let global_epoch = global::get().epoch.load(Relaxed); if global_epoch != self.epoch.load(Relaxed) { self.epoch.store(global_epoch, Relaxed); unsafe { (*self.garbage.get()).collect(); } } true } /// Exit the current (nested) critical section. pub fn exit(&self) { let new_count = self.in_critical.load(Relaxed) - 1; self.in_critical.store( new_count, if new_count > 0 { Relaxed } else { Release }); } /// Begin the reclamation process for a piece of data. pub unsafe fn reclaim(&self, data: *mut T) { (*self.garbage.get()).insert(data); } /// Attempt to collect garbage by moving the global epoch forward. /// /// Returns `true` on success. pub fn try_collect(&self, guard: &Guard) -> bool { let cur_epoch = global::get().epoch.load(SeqCst); for p in global::get().participants.iter(guard) { if p.in_critical.load(Relaxed) > 0 && p.epoch.load(Relaxed) != cur_epoch { return false } } let new_epoch = cur_epoch.wrapping_add(1); atomic::fence(Acquire); if global::get().epoch.compare_and_swap(cur_epoch, new_epoch, SeqCst) != cur_epoch { return false } unsafe { (*self.garbage.get()).collect(); global::get().garbage[new_epoch.wrapping_add(1) % 3].collect(); } self.epoch.store(new_epoch, Release); true } /// Move the current thread-local garbage into the global garbage bags. pub fn migrate_garbage(&self) { let cur_epoch = self.epoch.load(Relaxed); let local = unsafe { mem::replace(&mut *self.garbage.get(), garbage::Local::new()) }; global::get().garbage[cur_epoch.wrapping_sub(1) % 3].insert(local.old); global::get().garbage[cur_epoch % 3].insert(local.cur); global::get().garbage[global::get().epoch.load(Relaxed) % 3].insert(local.new); } /// How much garbage is this participant currently storing? pub fn garbage_size(&self) -> usize { unsafe { (*self.garbage.get()).size() } } /// Is this participant past its local GC threshhold? pub fn should_gc(&self) -> bool { self.garbage_size() >= GC_THRESH } } crossbeam-0.3.2/src/epoch/participants.rs010066400017510001751000000065071322354550400166660ustar0000000000000000// Manages the global participant list, which is an intrustive list in // which items are lazily removed on traversal (after being // "logically" deleted by becoming inactive.) use std::mem; use std::ops::{Deref, DerefMut}; use std::sync::atomic::Ordering::{Relaxed, Acquire, Release}; use epoch::{Atomic, Owned, Guard}; use epoch::participant::Participant; use CachePadded; /// Global, threadsafe list of threads participating in epoch management. #[derive(Debug)] pub struct Participants { head: Atomic } #[derive(Debug)] pub struct ParticipantNode(CachePadded); impl ParticipantNode { pub fn new() -> ParticipantNode { ParticipantNode(CachePadded::new(Participant::new())) } } impl Deref for ParticipantNode { type Target = Participant; fn deref(&self) -> &Participant { &self.0 } } impl DerefMut for ParticipantNode { fn deref_mut(&mut self) -> &mut Participant { &mut self.0 } } impl Participants { #[cfg(not(feature = "nightly"))] pub fn new() -> Participants { Participants { head: Atomic::null() } } #[cfg(feature = "nightly")] pub const fn new() -> Participants { Participants { head: Atomic::null() } } /// Enroll a new thread in epoch management by adding a new `Particpant` /// record to the global list. pub fn enroll(&self) -> *const Participant { let mut participant = Owned::new(ParticipantNode::new()); // we ultimately use epoch tracking to free Participant nodes, but we // can't actually enter an epoch here, so fake it; we know the node // can't be removed until marked inactive anyway. let fake_guard = (); let g: &'static Guard = unsafe { mem::transmute(&fake_guard) }; loop { let head = self.head.load(Relaxed, g); participant.next.store_shared(head, Relaxed); match self.head.cas_and_ref(head, participant, Release, g) { Ok(shared) => { let shared: &Participant = &shared; return shared; } Err(owned) => { participant = owned; } } } } pub fn iter<'a>(&'a self, g: &'a Guard) -> Iter<'a> { Iter { guard: g, next: &self.head, needs_acq: true, } } } #[derive(Debug)] pub struct Iter<'a> { // pin to an epoch so that we can free inactive nodes guard: &'a Guard, next: &'a Atomic, // an Acquire read is needed only for the first read, due to release // sequences needs_acq: bool, } impl<'a> Iterator for Iter<'a> { type Item = &'a Participant; fn next(&mut self) -> Option<&'a Participant> { let mut cur = if self.needs_acq { self.needs_acq = false; self.next.load(Acquire, self.guard) } else { self.next.load(Relaxed, self.guard) }; while let Some(n) = cur { // attempt to clean up inactive nodes if !n.active.load(Relaxed) { cur = n.next.load(Relaxed, self.guard); // TODO: actually reclaim inactive participants! } else { self.next = &n.next; return Some(&n) } } None } } crossbeam-0.3.2/src/lib.rs010066400017510001751000000045131322354550400136300ustar0000000000000000//! Support for concurrent and parallel programming. //! //! This crate is an early work in progress. The focus for the moment is //! concurrency: //! //! - **Non-blocking data structures**. These data structures allow for high //! performance, highly-concurrent access, much superior to wrapping with a //! `Mutex`. Ultimately the goal is to include stacks, queues, deques, bags, //! sets and maps. These live in the `sync` module. //! //! - **Memory management**. Because non-blocking data structures avoid global //! synchronization, it is not easy to tell when internal data can be safely //! freed. The `mem` module provides generic, easy to use, and high-performance //! APIs for managing memory in these cases. These live in the `mem` module. //! //! - **Synchronization**. The standard library provides a few synchronization //! primitives (locks, barriers, etc) but this crate seeks to expand that set //! to include more advanced/niche primitives, as well as userspace //! alternatives. These live in the `sync` module. //! //! - **Scoped thread API**. Finally, the crate provides a "scoped" thread API, //! making it possible to spawn threads that share stack data with their //! parents. This functionality is exported at the top-level. //#![deny(missing_docs)] #![cfg_attr(feature = "nightly", feature(const_fn, repr_simd, optin_builtin_traits))] use std::thread; use std::io; pub use scoped::{scope, Scope, ScopedJoinHandle}; pub mod epoch; pub mod sync; mod scoped; mod cache_padded; pub use self::cache_padded::{CachePadded, ZerosValid}; #[doc(hidden)] trait FnBox { fn call_box(self: Box); } impl FnBox for F { fn call_box(self: Box) { (*self)() } } /// Like `std::thread::spawn`, but without the closure bounds. pub unsafe fn spawn_unsafe<'a, F>(f: F) -> thread::JoinHandle<()> where F: FnOnce() + Send + 'a { let builder = thread::Builder::new(); builder_spawn_unsafe(builder, f).unwrap() } /// Like `std::thread::Builder::spawn`, but without the closure bounds. pub unsafe fn builder_spawn_unsafe<'a, F>(builder: thread::Builder, f: F) -> io::Result> where F: FnOnce() + Send + 'a { use std::mem; let closure: Box = Box::new(f); let closure: Box = mem::transmute(closure); builder.spawn(move || closure.call_box()) } crossbeam-0.3.2/src/scoped.rs010066400017510001751000000222301322354550400143330ustar0000000000000000use std::cell::RefCell; use std::fmt; use std::mem; use std::rc::Rc; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; use std::io; use {builder_spawn_unsafe, FnBox}; use sync::AtomicOption; pub struct Scope<'a> { dtors: RefCell>> } struct DtorChain<'a> { dtor: Box, next: Option>> } enum JoinState { Running(thread::JoinHandle<()>), Joined, } impl JoinState { fn join(&mut self) { let mut state = JoinState::Joined; mem::swap(self, &mut state); if let JoinState::Running(handle) = state { let res = handle.join(); if !thread::panicking() { res.unwrap(); } } } } /// A handle to a scoped thread pub struct ScopedJoinHandle { inner: Rc>, packet: Arc>, thread: thread::Thread, } /// Create a new `scope`, for deferred destructors. /// /// Scopes, in particular, support [*scoped thread spawning*](struct.Scope.html#method.spawn). /// /// # Examples /// /// Creating and using a scope: /// /// ``` /// crossbeam::scope(|scope| { /// scope.defer(|| println!("Exiting scope")); /// scope.spawn(|| println!("Running child thread in scope")) /// }); /// // Prints messages in the reverse order written /// ``` pub fn scope<'a, F, R>(f: F) -> R where F: FnOnce(&Scope<'a>) -> R { let mut scope = Scope { dtors: RefCell::new(None) }; let ret = f(&scope); scope.drop_all(); ret } impl<'a> fmt::Debug for Scope<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Scope {{ ... }}") } } impl fmt::Debug for ScopedJoinHandle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ScopedJoinHandle {{ ... }}") } } impl<'a> Scope<'a> { // This method is carefully written in a transactional style, so // that it can be called directly and, if any dtor panics, can be // resumed in the unwinding this causes. By initially running the // method outside of any destructor, we avoid any leakage problems // due to @rust-lang/rust#14875. fn drop_all(&mut self) { loop { // use a separate scope to ensure that the RefCell borrow // is relinquished before running `dtor` let dtor = { let mut dtors = self.dtors.borrow_mut(); if let Some(mut node) = dtors.take() { *dtors = node.next.take().map(|b| *b); node.dtor } else { return } }; dtor.call_box() } } /// Schedule code to be executed when exiting the scope. /// /// This is akin to having a destructor on the stack, except that it is /// *guaranteed* to be run. pub fn defer(&self, f: F) where F: FnOnce() + 'a { let mut dtors = self.dtors.borrow_mut(); *dtors = Some(DtorChain { dtor: Box::new(f), next: dtors.take().map(Box::new) }); } /// Create a scoped thread. /// /// `spawn` is similar to the [`spawn`][spawn] function in Rust's standard library. The /// difference is that this thread is scoped, meaning that it's guaranteed to terminate /// before the current stack frame goes away, allowing you to reference the parent stack frame /// directly. This is ensured by having the parent thread join on the child thread before the /// scope exits. /// /// [spawn]: http://doc.rust-lang.org/std/thread/fn.spawn.html /// /// # Examples /// /// A basic scoped thread: /// /// ``` /// crossbeam::scope(|scope| { /// scope.spawn(|| { /// println!("Hello from a scoped thread!"); /// }); /// }); /// ``` /// /// When writing concurrent Rust programs, you'll sometimes see a pattern like this, using /// [`std::thread::spawn`][spawn]: /// /// ```ignore /// let array = [1, 2, 3]; /// let mut guards = vec![]; /// /// for i in &array { /// let guard = std::thread::spawn(move || { /// println!("element: {}", i); /// }); /// /// guards.push(guard); /// } /// /// for guard in guards { /// guard.join().unwrap(); /// } /// ``` /// /// The basic pattern is: /// /// 1. Iterate over some collection. /// 2. Spin up a thread to operate on each part of the collection. /// 3. Join all the threads. /// /// However, this code actually gives an error: /// /// ```text /// error: `array` does not live long enough /// for i in &array { /// ^~~~~ /// in expansion of for loop expansion /// note: expansion site /// note: reference must be valid for the static lifetime... /// note: ...but borrowed value is only valid for the block suffix following statement 0 at ... /// let array = [1, 2, 3]; /// let mut guards = vec![]; /// /// for i in &array { /// let guard = std::thread::spawn(move || { /// println!("element: {}", i); /// ... /// error: aborting due to previous error /// ``` /// /// Because [`std::thread::spawn`][spawn] doesn't know about this scope, it requires a /// `'static` lifetime. One way of giving it a proper lifetime is to use an [`Arc`][arc]: /// /// [arc]: http://doc.rust-lang.org/stable/std/sync/struct.Arc.html /// /// ``` /// use std::sync::Arc; /// /// let array = Arc::new([1, 2, 3]); /// let mut guards = vec![]; /// /// for i in 0..array.len() { /// let a = array.clone(); /// /// let guard = std::thread::spawn(move || { /// println!("element: {}", a[i]); /// }); /// /// guards.push(guard); /// } /// /// for guard in guards { /// guard.join().unwrap(); /// } /// ``` /// /// But this introduces unnecessary allocation, as `Arc` puts its data on the heap, and we /// also end up dealing with reference counts. We know that we're joining the threads before /// our function returns, so just taking a reference _should_ be safe. Rust can't know that, /// though. /// /// Enter scoped threads. Here's our original example, using `spawn` from crossbeam rather /// than from `std::thread`: /// /// ``` /// let array = [1, 2, 3]; /// /// crossbeam::scope(|scope| { /// for i in &array { /// scope.spawn(move || { /// println!("element: {}", i); /// }); /// } /// }); /// ``` /// /// Much more straightforward. pub fn spawn(&self, f: F) -> ScopedJoinHandle where F: FnOnce() -> T + Send + 'a, T: Send + 'a { self.builder().spawn(f).unwrap() } /// Generates the base configuration for spawning a scoped thread, from which configuration /// methods can be chained. pub fn builder<'s>(&'s self) -> ScopedThreadBuilder<'s, 'a> { ScopedThreadBuilder { scope: self, builder: thread::Builder::new(), } } } /// Scoped thread configuration. Provides detailed control over the properties and behavior of new /// scoped threads. pub struct ScopedThreadBuilder<'s, 'a: 's> { scope: &'s Scope<'a>, builder: thread::Builder, } impl<'s, 'a: 's> ScopedThreadBuilder<'s, 'a> { /// Names the thread-to-be. Currently the name is used for identification only in panic /// messages. pub fn name(mut self, name: String) -> ScopedThreadBuilder<'s, 'a> { self.builder = self.builder.name(name); self } /// Sets the size of the stack for the new thread. pub fn stack_size(mut self, size: usize) -> ScopedThreadBuilder<'s, 'a> { self.builder = self.builder.stack_size(size); self } /// Spawns a new thread, and returns a join handle for it. pub fn spawn(self, f: F) -> io::Result> where F: FnOnce() -> T + Send + 'a, T: Send + 'a { let their_packet = Arc::new(AtomicOption::new()); let my_packet = their_packet.clone(); let join_handle = try!(unsafe { builder_spawn_unsafe(self.builder, move || { their_packet.swap(f(), Ordering::Relaxed); }) }); let thread = join_handle.thread().clone(); let deferred_handle = Rc::new(RefCell::new(JoinState::Running(join_handle))); let my_handle = deferred_handle.clone(); self.scope.defer(move || { let mut state = deferred_handle.borrow_mut(); state.join(); }); Ok(ScopedJoinHandle { inner: my_handle, packet: my_packet, thread: thread, }) } } impl ScopedJoinHandle { /// Join the scoped thread, returning the result it produced. pub fn join(self) -> T { self.inner.borrow_mut().join(); self.packet.take(Ordering::Relaxed).unwrap() } /// Get the underlying thread handle. pub fn thread(&self) -> &thread::Thread { &self.thread } } impl<'a> Drop for Scope<'a> { fn drop(&mut self) { self.drop_all() } } crossbeam-0.3.2/src/sync/arc_cell.rs010066400017510001751000000042451322354373700156120ustar0000000000000000use std::marker::PhantomData; use std::mem; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; /// A type providing atomic storage and retrieval of an `Arc`. #[derive(Debug)] pub struct ArcCell(AtomicUsize, PhantomData>); impl Drop for ArcCell { fn drop(&mut self) { self.take(); } } impl ArcCell { /// Creates a new `ArcCell`. pub fn new(t: Arc) -> ArcCell { ArcCell(AtomicUsize::new(unsafe { mem::transmute(t) }), PhantomData) } fn take(&self) -> Arc { loop { match self.0.swap(0, Ordering::Acquire) { 0 => {} n => return unsafe { mem::transmute(n) } } } } fn put(&self, t: Arc) { debug_assert_eq!(self.0.load(Ordering::SeqCst), 0); self.0.store(unsafe { mem::transmute(t) }, Ordering::Release); } /// Stores a new value in the `ArcCell`, returning the previous /// value. pub fn set(&self, t: Arc) -> Arc { let old = self.take(); self.put(t); old } /// Returns a copy of the value stored by the `ArcCell`. pub fn get(&self) -> Arc { let t = self.take(); // NB: correctness here depends on Arc's clone impl not panicking let out = t.clone(); self.put(t); out } } #[cfg(test)] mod test { use std::sync::Arc; use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; use super::*; #[test] fn basic() { let r = ArcCell::new(Arc::new(0)); assert_eq!(*r.get(), 0); assert_eq!(*r.set(Arc::new(1)), 0); assert_eq!(*r.get(), 1); } #[test] fn drop_runs() { static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; struct Foo; impl Drop for Foo { fn drop(&mut self) { DROPS.fetch_add(1, Ordering::SeqCst); } } let r = ArcCell::new(Arc::new(Foo)); let _f = r.get(); r.get(); r.set(Arc::new(Foo)); drop(_f); assert_eq!(DROPS.load(Ordering::SeqCst), 1); drop(r); assert_eq!(DROPS.load(Ordering::SeqCst), 2); } } crossbeam-0.3.2/src/sync/atomic_option.rs010066400017510001751000000024001322354550400166730ustar0000000000000000use std::sync::atomic::{AtomicPtr, Ordering}; use std::ptr; unsafe impl Send for AtomicOption {} unsafe impl Sync for AtomicOption {} #[derive(Debug)] pub struct AtomicOption { inner: AtomicPtr, } impl Drop for AtomicOption { fn drop(&mut self) { let inner = self.inner.load(Ordering::Relaxed); if !inner.is_null() { unsafe { drop(Box::from_raw(inner)); } } } } impl AtomicOption { pub fn new() -> AtomicOption { AtomicOption { inner: AtomicPtr::new(ptr::null_mut()) } } fn swap_inner(&self, ptr: *mut T, order: Ordering) -> Option> { let old = self.inner.swap(ptr, order); if old.is_null() { None } else { Some(unsafe { Box::from_raw(old) }) } } // allows re-use of allocation pub fn swap_box(&self, t: Box, order: Ordering) -> Option> { self.swap_inner(Box::into_raw(t), order) } pub fn swap(&self, t: T, order: Ordering) -> Option { self.swap_box(Box::new(t), order).map(|old| *old) } pub fn take(&self, order: Ordering) -> Option { self.swap_inner(ptr::null_mut(), order).map(|old| *old) } } crossbeam-0.3.2/src/sync/chase_lev.rs010066400017510001751000000441171322354550400157730ustar0000000000000000// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A lock-free concurrent work-stealing deque //! //! This module contains a hybrid implementation of the Chase-Lev work stealing deque //! described in ["Dynamic Circular Work-Stealing Deque"][chase_lev] and the improved version //! described in ["Correct and Efficient Work-Stealing for Weak Memory Models"][weak_chase_lev]. //! The implementation is heavily based on the pseudocode found in the papers. //! //! # Example //! //! ``` //! use crossbeam::sync::chase_lev; //! let (worker, stealer) = chase_lev::deque(); //! //! // Only the worker may push/try_pop //! worker.push(1); //! worker.try_pop(); //! //! // Stealers take data from the other end of the deque //! worker.push(1); //! stealer.steal(); //! //! // Stealers can be cloned to have many stealers stealing in parallel //! worker.push(1); //! let stealer2 = stealer.clone(); //! stealer2.steal(); //! ``` //! //! [chase_lev]: http://neteril.org/~jeremie/Dynamic_Circular_Work_Queue.pdf //! [weak_chase_lev]: http://www.di.ens.fr/~zappa/readings/ppopp13.pdf use std::cell::UnsafeCell; use std::fmt; use std::mem; use std::ptr; use std::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst}; use std::sync::atomic::{AtomicIsize, fence}; use std::sync::Arc; use std::marker::PhantomData; use std::cell::Cell; use epoch::{self, Atomic, Shared, Owned}; // Once the queue is less than 1/K full, then it will be downsized. Note that // the deque requires that this number be less than 2. const K: isize = 4; // Minimum number of bits that a buffer size should be. No buffer will resize to // under this value, and all deques will initially contain a buffer of this // size. // // The size in question is 1 << MIN_BITS const MIN_BITS: u32 = 7; #[derive(Debug)] struct Deque { bottom: AtomicIsize, top: AtomicIsize, array: Atomic>, } // FIXME: can these constraints be relaxed? unsafe impl Send for Deque {} unsafe impl Sync for Deque {} /// Worker half of the work-stealing deque. This worker has exclusive access to /// one side of the deque, and uses `push` and `try_pop` method to manipulate it. /// /// There may only be one worker per deque, so `Worker` does not implement /// `Clone` or `Copy`. #[derive(Debug)] pub struct Worker { deque: Arc>, // Marker so that the Worker is Send but not Sync. The worker can only be // accessed from a single thread at once. Ideally we would use a negative // impl here but these are not stable yet. marker: PhantomData>, } /// The stealing half of the work-stealing deque. Stealers have access to the /// opposite end of the deque from the worker, and they only have access to the /// `steal` method. /// /// Stealers can be cloned to have more than one handle active at a time. #[derive(Debug)] pub struct Stealer { deque: Arc>, } /// When stealing some data, this is an enumeration of the possible outcomes. #[derive(PartialEq, Eq, Debug)] pub enum Steal { /// The deque was empty at the time of stealing Empty, /// The stealer lost the race for stealing data, and a retry may return more /// data. Abort, /// The stealer has successfully stolen some data. Data(T), } // An internal buffer used by the chase-lev deque. This structure is actually // implemented as a circular buffer, and is used as the intermediate storage of // the data in the deque. // // This Vec always has a length of 0, the backing buffer is just used by the // code below. struct Buffer { storage: UnsafeCell>, log_size: u32, } impl fmt::Debug for Buffer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Buffer {{ ... }}") } } impl Worker { /// Pushes data onto the front of this work queue. pub fn push(&self, t: T) { unsafe { self.deque.push(t) } } /// Pops data off the front of the work queue, returning `None` on an empty /// queue. pub fn try_pop(&self) -> Option { unsafe { self.deque.try_pop() } } } impl Stealer { /// Steals work off the end of the queue (opposite of the worker's end) pub fn steal(&self) -> Steal { self.deque.steal() } } impl Clone for Stealer { fn clone(&self) -> Stealer { Stealer { deque: self.deque.clone() } } } /// Creates a new empty deque pub fn deque() -> (Worker, Stealer) { let a = Arc::new(Deque::new()); let b = a.clone(); (Worker { deque: a, marker: PhantomData }, Stealer { deque: b }) } // Almost all of this code can be found directly in the paper so I'm not // personally going to heavily comment what's going on here. impl Deque { fn new() -> Deque { let array = Atomic::null(); array.store(Some(Owned::new(Buffer::new(MIN_BITS))), SeqCst); Deque { bottom: AtomicIsize::new(0), top: AtomicIsize::new(0), array: array, } } unsafe fn push(&self, data: T) { let guard = epoch::pin(); let mut b = self.bottom.load(Relaxed); let t = self.top.load(Acquire); let mut a = self.array.load(Relaxed, &guard).unwrap(); let size = b - t; if size >= (a.size() as isize) - 1 { // You won't find this code in the chase-lev deque paper. This is // alluded to in a small footnote, however. We always free a buffer // when growing in order to prevent leaks. a = self.swap_buffer(a, a.resize(b, t, 1), &guard); // reload the bottom counter, since swap_buffer modifies it. b = self.bottom.load(Relaxed); } a.put(b, data); fence(Release); self.bottom.store(b + 1, Relaxed); } unsafe fn try_pop(&self) -> Option { let guard = epoch::pin(); let b = self.bottom.load(Relaxed); let a = self.array.load(Relaxed, &guard).unwrap(); self.bottom.store(b - 1, Relaxed); fence(SeqCst); // the store to bottom must occur before loading top. let t = self.top.load(Relaxed); let size = b - t; if size <= 0 { // empty queue. revert the decrement of bottom. self.bottom.store(b, Relaxed); None } else if size >= 2 { // non-racy case. return the data let data = a.get(b - 1); self.maybe_shrink(b - 1, t, &guard); Some(data) } else { // racy case. race against steals. let success = self.top.compare_and_swap(t, t + 1, SeqCst) == t; // set the queue to a canonically empty state. self.bottom.store(b, Relaxed); if success { Some(a.get(t)) } else { None } } } fn steal(&self) -> Steal { let guard = epoch::pin(); let t = self.top.load(Relaxed); fence(SeqCst); // top must be loaded before bottom. let b = self.bottom.load(Acquire); let size = b - t; if size <= 0 { return Steal::Empty } unsafe { // while the paper uses a "consume" ordering here, the closest thing we have // available is Acquire, which is strictly stronger. let a = self.array.load(Acquire, &guard).unwrap(); let data = a.get(t); // we may be racing against other steals and a pop. if self.top.compare_and_swap(t, t + 1, SeqCst) == t { Steal::Data(data) } else { mem::forget(data); // someone else stole this value Steal::Abort } } } // potentially shrink the array. This can be called only from the worker. unsafe fn maybe_shrink(&self, b: isize, t: isize, guard: &epoch::Guard) { let a = self.array.load(SeqCst, guard).unwrap(); let size = b - t; if size < (a.size() as isize) / K && size > (1 << MIN_BITS) { self.swap_buffer(a, a.resize(b, t, -1), guard); } } // Helper routine not mentioned in the paper which is used in growing and // shrinking buffers to swap in a new buffer into place. // // As a bit of a recap, stealers can continue using buffers after this // method has called 'unlinked' on it. The continued usage is simply a read // followed by a forget, but we must make sure that the memory can continue // to be read after we flag this buffer for reclamation. All stealers, // however, have their own epoch pinned during this time so the buffer will // just naturally be free'd once all concurrent stealers have exited. // // This method may only be called safely from the workers due to the way it modifies // the array pointer. unsafe fn swap_buffer<'a>(&self, old: Shared<'a, Buffer>, buf: Buffer, guard: &'a epoch::Guard) -> Shared<'a, Buffer> { let newbuf = Owned::new(buf); let newbuf = self.array.store_and_ref(newbuf, Release, &guard); guard.unlinked(old); newbuf } } impl Drop for Deque { fn drop(&mut self) { let guard = epoch::pin(); // Arc enforces that we have truly exclusive access here. let t = self.top.load(Relaxed); let b = self.bottom.load(Relaxed); let a = self.array.swap(None, Relaxed, &guard).unwrap(); // Free whatever is leftover in the dequeue, then free the backing // memory itself unsafe { for i in t..b { drop(a.get(i)); } guard.unlinked(a); } } } impl Buffer { fn new(log_size: u32) -> Buffer { Buffer { storage: UnsafeCell::new(Vec::with_capacity(1 << log_size)), log_size: log_size, } } fn size(&self) -> usize { unsafe { (*self.storage.get()).capacity() } } fn mask(&self) -> isize { unsafe { ((*self.storage.get()).capacity() - 1) as isize } } unsafe fn elem(&self, i: isize) -> *mut T { (*self.storage.get()).as_mut_ptr().offset(i & self.mask()) } // This does not protect against loading duplicate values of the same cell, // nor does this clear out the contents contained within. Hence, this is a // very unsafe method which the caller needs to treat specially in case a // race is lost. unsafe fn get(&self, i: isize) -> T { ptr::read(self.elem(i)) } // Unsafe because this unsafely overwrites possibly uninitialized or // initialized data. unsafe fn put(&self, i: isize, t: T) { ptr::write(self.elem(i), t); } // Again, unsafe because this has incredibly dubious ownership violations. // It is assumed that this buffer is immediately dropped. unsafe fn resize(&self, b: isize, t: isize, delta: i32) -> Buffer { let buf = Buffer::new(((self.log_size as i32) + delta) as u32); for i in t..b { buf.put(i, self.get(i)); } return buf; } } #[cfg(test)] mod tests { extern crate rand; use super::{deque, Worker, Stealer, Steal}; use std::thread; use std::sync::Arc; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, AtomicUsize, ATOMIC_USIZE_INIT}; use std::sync::atomic::Ordering::SeqCst; use self::rand::Rng; #[test] fn smoke() { let (w, s) = deque(); assert_eq!(w.try_pop(), None); assert_eq!(s.steal(), Steal::Empty); w.push(1); assert_eq!(w.try_pop(), Some(1)); w.push(1); assert_eq!(s.steal(), Steal::Data(1)); w.push(1); assert_eq!(s.clone().steal(), Steal::Data(1)); } #[test] fn stealpush() { static AMT: isize = 100000; let (w, s) = deque(); let t = thread::spawn(move || { let mut left = AMT; while left > 0 { match s.steal() { Steal::Data(i) => { assert_eq!(i, 1); left -= 1; } Steal::Abort | Steal::Empty => {} } } }); for _ in 0..AMT { w.push(1); } t.join().unwrap(); } #[test] fn stealpush_large() { static AMT: isize = 100000; let (w, s) = deque(); let t = thread::spawn(move || { let mut left = AMT; while left > 0 { match s.steal() { Steal::Data((1, 10)) => { left -= 1; } Steal::Data(..) => panic!(), Steal::Abort | Steal::Empty => {} } } }); for _ in 0..AMT { w.push((1, 10)); } t.join().unwrap(); } fn stampede(w: Worker>, s: Stealer>, nthreads: isize, amt: usize) { for _ in 0..amt { w.push(Box::new(20)); } let remaining = Arc::new(AtomicUsize::new(amt)); let threads = (0..nthreads).map(|_| { let remaining = remaining.clone(); let s = s.clone(); thread::spawn(move || { while remaining.load(SeqCst) > 0 { match s.steal() { Steal::Data(val) => { if *val == 20 { remaining.fetch_sub(1, SeqCst); } else { panic!() } } Steal::Abort | Steal::Empty => {} } } }) }).collect::>(); while remaining.load(SeqCst) > 0 { if let Some(val) = w.try_pop() { if *val == 20 { remaining.fetch_sub(1, SeqCst); } else { panic!() } } } for thread in threads.into_iter() { thread.join().unwrap(); } } #[test] fn run_stampede() { let (w, s) = deque(); stampede(w, s, 8, 10000); } #[test] fn many_stampede() { static AMT: usize = 4; let threads = (0..AMT).map(|_| { let (w, s) = deque(); thread::spawn(|| { stampede(w, s, 4, 10000); }) }).collect::>(); for thread in threads.into_iter() { thread.join().unwrap(); } } #[test] fn stress() { static AMT: isize = 100000; static NTHREADS: isize = 8; static DONE: AtomicBool = ATOMIC_BOOL_INIT; static HITS: AtomicUsize = ATOMIC_USIZE_INIT; let (w, s) = deque(); let threads = (0..NTHREADS).map(|_| { let s = s.clone(); thread::spawn(move || { loop { match s.steal() { Steal::Data(2) => { HITS.fetch_add(1, SeqCst); } Steal::Data(..) => panic!(), _ if DONE.load(SeqCst) => break, _ => {} } } }) }).collect::>(); let mut rng = rand::thread_rng(); let mut expected = 0; while expected < AMT { if rng.gen_range(0, 3) == 2 { match w.try_pop() { None => {} Some(2) => { HITS.fetch_add(1, SeqCst); }, Some(_) => panic!(), } } else { expected += 1; w.push(2); } } while HITS.load(SeqCst) < AMT as usize { match w.try_pop() { None => {} Some(2) => { HITS.fetch_add(1, SeqCst); }, Some(_) => panic!(), } } DONE.store(true, SeqCst); for thread in threads.into_iter() { thread.join().unwrap(); } assert_eq!(HITS.load(SeqCst), expected as usize); } #[test] fn no_starvation() { static AMT: isize = 10000; static NTHREADS: isize = 4; static DONE: AtomicBool = ATOMIC_BOOL_INIT; let (w, s) = deque(); let (threads, hits): (Vec<_>, Vec<_>) = (0..NTHREADS).map(|_| { let s = s.clone(); let ctr = Arc::new(AtomicUsize::new(0)); let ctr2 = ctr.clone(); (thread::spawn(move || { loop { match s.steal() { Steal::Data((1, 2)) => { ctr.fetch_add(1, SeqCst); } Steal::Data(..) => panic!(), _ if DONE.load(SeqCst) => break, _ => {} } } }), ctr2) }).unzip(); let mut rng = rand::thread_rng(); let mut myhit = false; 'outer: loop { for _ in 0..rng.gen_range(0, AMT) { if !myhit && rng.gen_range(0, 3) == 2 { match w.try_pop() { None => {} Some((1, 2)) => myhit = true, Some(_) => panic!(), } } else { w.push((1, 2)); } } for slot in hits.iter() { let amt = slot.load(SeqCst); if amt == 0 { continue 'outer; } } if myhit { break } } DONE.store(true, SeqCst); for thread in threads.into_iter() { thread.join().unwrap(); } } } crossbeam-0.3.2/src/sync/mod.rs010066400017510001751000000005011322354373700146140ustar0000000000000000//! Synchronization primitives. pub use self::ms_queue::MsQueue; pub use self::atomic_option::AtomicOption; pub use self::treiber_stack::TreiberStack; pub use self::seg_queue::SegQueue; pub use self::arc_cell::ArcCell; mod atomic_option; mod ms_queue; mod treiber_stack; mod seg_queue; pub mod chase_lev; mod arc_cell; crossbeam-0.3.2/src/sync/ms_queue.rs010066400017510001751000000376751322354550400157000ustar0000000000000000use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; use std::sync::atomic::AtomicBool; use std::{ptr, mem}; use std::thread::{self, Thread}; use epoch::{self, Atomic, Owned, Shared}; use CachePadded; /// A Michael-Scott lock-free queue, with support for blocking `pop`s. /// /// Usable with any number of producers and consumers. // The representation here is a singly-linked list, with a sentinel // node at the front. In general the `tail` pointer may lag behind the // actual tail. Non-sentinel nodes are either all `Data` or all // `Blocked` (requests for data from blocked threads). #[derive(Debug)] pub struct MsQueue { head: CachePadded>>, tail: CachePadded>>, } #[derive(Debug)] struct Node { payload: Payload, next: Atomic>, } #[derive(Debug)] enum Payload { /// A node with actual data that can be popped. Data(T), /// A node representing a blocked request for data. Blocked(*mut Signal), } /// A blocked request for data, which includes a slot to write the data. #[derive(Debug)] struct Signal { /// Thread to unpark when data is ready. thread: Thread, /// The actual data, when available. data: Option, /// Is the data ready? Needed to cope with spurious wakeups. ready: AtomicBool, } impl Node { fn is_data(&self) -> bool { if let Payload::Data(_) = self.payload { true } else { false } } } // Any particular `T` should never accessed concurrently, so no need // for Sync. unsafe impl Sync for MsQueue {} unsafe impl Send for MsQueue {} impl MsQueue { /// Create a new, empty queue. pub fn new() -> MsQueue { let q = MsQueue { head: CachePadded::new(Atomic::null()), tail: CachePadded::new(Atomic::null()), }; let sentinel = Owned::new(Node { payload: Payload::Data(unsafe { mem::uninitialized() }), next: Atomic::null(), }); let guard = epoch::pin(); let sentinel = q.head.store_and_ref(sentinel, Relaxed, &guard); q.tail.store_shared(Some(sentinel), Relaxed); q } #[inline(always)] /// Attempt to atomically place `n` into the `next` pointer of `onto`. /// /// If unsuccessful, returns ownership of `n`, possibly updating /// the queue's `tail` pointer. fn push_internal(&self, guard: &epoch::Guard, onto: Shared>, n: Owned>) -> Result<(), Owned>> { // is `onto` the actual tail? if let Some(next) = onto.next.load(Acquire, guard) { // if not, try to "help" by moving the tail pointer forward self.tail.cas_shared(Some(onto), Some(next), Release); Err(n) } else { // looks like the actual tail; attempt to link in `n` onto.next.cas_and_ref(None, n, Release, guard).map(|shared| { // try to move the tail pointer forward self.tail.cas_shared(Some(onto), Some(shared), Release); }) } } /// Add `t` to the back of the queue, possibly waking up threads /// blocked on `pop`. pub fn push(&self, t: T) { /// We may or may not need to allocate a node; once we do, /// we cache that allocation. enum Cache { Data(T), Node(Owned>), } impl Cache { /// Extract the node if cached, or allocate if not. fn into_node(self) -> Owned> { match self { Cache::Data(t) => { Owned::new(Node { payload: Payload::Data(t), next: Atomic::null() }) } Cache::Node(n) => n } } /// Extract the data from the cache, deallocating any cached node. fn into_data(self) -> T { match self { Cache::Data(t) => t, Cache::Node(node) => { match node.into_inner().payload { Payload::Data(t) => t, _ => unreachable!(), } } } } } let mut cache = Cache::Data(t); // don't allocate up front let guard = epoch::pin(); loop { // We push onto the tail, so we'll start optimistically by looking // there first. let tail = self.tail.load(Acquire, &guard).unwrap(); // Is the queue in Data mode (empty queues can be viewed as either mode)? if tail.is_data() || self.head.load(Relaxed, &guard).unwrap().as_raw() == tail.as_raw() { // Attempt to push onto the `tail` snapshot; fails if // `tail.next` has changed, which will always be the case if the // queue has transitioned to blocking mode. match self.push_internal(&guard, tail, cache.into_node()) { Ok(_) => return, Err(n) => { // replace the cache, retry whole thing cache = Cache::Node(n) } } } else { // Queue is in blocking mode. Attempt to unblock a thread. let head = self.head.load(Acquire, &guard).unwrap(); // Get a handle on the first blocked node. Racy, so queue might // be empty or in data mode by the time we see it. let request = head.next.load(Acquire, &guard).and_then(|next| { match next.payload { Payload::Blocked(signal) => Some((next, signal)), Payload::Data(_) => None, } }); if let Some((blocked_node, signal)) = request { // race to dequeue the node if self.head.cas_shared(Some(head), Some(blocked_node), Release) { unsafe { // signal the thread (*signal).data = Some(cache.into_data()); let thread = (*signal).thread.clone(); (*signal).ready.store(true, Release); thread.unpark(); guard.unlinked(head); return; } } } } } } #[inline(always)] // Attempt to pop a data node. `Ok(None)` if queue is empty or in blocking // mode; `Err(())` if lost race to pop. fn pop_internal(&self, guard: &epoch::Guard) -> Result, ()> { let head = self.head.load(Acquire, guard).unwrap(); if let Some(next) = head.next.load(Acquire, guard) { if let Payload::Data(ref t) = next.payload { unsafe { if self.head.cas_shared(Some(head), Some(next), Release) { guard.unlinked(head); Ok(Some(ptr::read(t))) } else { Err(()) } } } else { Ok(None) } } else { Ok(None) } } /// Check if this queue is empty. pub fn is_empty(&self) -> bool { let guard = epoch::pin(); let head = self.head.load(Acquire, &guard).unwrap(); if let Some(next) = head.next.load(Acquire, &guard) { if let Payload::Data(_) = next.payload { false } else { true } } else { true } } /// Attempt to dequeue from the front. /// /// Returns `None` if the queue is observed to be empty. pub fn try_pop(&self) -> Option { let guard = epoch::pin(); loop { if let Ok(r) = self.pop_internal(&guard) { return r; } } } /// Dequeue an element from the front of the queue, blocking if the queue is /// empty. pub fn pop(&self) -> T { let guard = epoch::pin(); // Fast path: keep retrying until we observe that the queue has no data, // avoiding the allocation of a blocked node. loop { match self.pop_internal(&guard) { Ok(Some(r)) => { return r; } Ok(None) => { break; } Err(()) => {} } } // The signal gets to live on the stack, since this stack frame will be // blocked until receiving the signal. let mut signal = Signal { thread: thread::current(), data: None, ready: AtomicBool::new(false), }; // Go ahead and allocate the blocked node; chances are, we'll need it. let mut node = Owned::new(Node { payload: Payload::Blocked(&mut signal), next: Atomic::null(), }); loop { // try a normal pop if let Ok(Some(r)) = self.pop_internal(&guard) { return r; } // At this point, we believe the queue is empty/blocked. // Snapshot the tail, onto which we want to push a blocked node. let tail = self.tail.load(Acquire, &guard).unwrap(); // Double-check that we're in blocking mode if tail.is_data() { // The current tail is in data mode, so we probably need to abort. // BUT, it might be the sentinel, so check for that first. let head = self.head.load(Relaxed, &guard).unwrap(); if tail.is_data() && tail.as_raw() != head.as_raw() { continue; } } // At this point, the tail snapshot is either a blocked node deep in // the queue, the sentinel, or no longer accessible from the queue. // In *ALL* of these cases, if we succeed in pushing onto the // snapshot, we know we are maintaining the core invariant: all // reachable, non-sentinel nodes have the same payload mode, in this // case, blocked. match self.push_internal(&guard, tail, node) { Ok(()) => { while !signal.ready.load(Acquire) { thread::park(); } return signal.data.unwrap(); } Err(n) => { node = n; } } } } } impl Drop for MsQueue { fn drop(&mut self) { while self.try_pop().is_some() {} // Destroy the remaining sentinel node. let guard = epoch::pin(); let sentinel = self.head.load(Relaxed, &guard).unwrap().as_raw(); unsafe { drop(Vec::from_raw_parts(sentinel, 0, 1)); } } } #[cfg(test)] mod test { const CONC_COUNT: i64 = 1000000; use scope; use super::*; #[test] fn push_try_pop_1() { let q: MsQueue = MsQueue::new(); assert!(q.is_empty()); q.push(37); assert!(!q.is_empty()); assert_eq!(q.try_pop(), Some(37)); assert!(q.is_empty()); } #[test] fn push_try_pop_2() { let q: MsQueue = MsQueue::new(); assert!(q.is_empty()); q.push(37); q.push(48); assert_eq!(q.try_pop(), Some(37)); assert!(!q.is_empty()); assert_eq!(q.try_pop(), Some(48)); assert!(q.is_empty()); } #[test] fn push_try_pop_many_seq() { let q: MsQueue = MsQueue::new(); assert!(q.is_empty()); for i in 0..200 { q.push(i) } assert!(!q.is_empty()); for i in 0..200 { assert_eq!(q.try_pop(), Some(i)); } assert!(q.is_empty()); } #[test] fn push_pop_1() { let q: MsQueue = MsQueue::new(); assert!(q.is_empty()); q.push(37); assert!(!q.is_empty()); assert_eq!(q.pop(), 37); assert!(q.is_empty()); } #[test] fn push_pop_2() { let q: MsQueue = MsQueue::new(); q.push(37); q.push(48); assert_eq!(q.pop(), 37); assert_eq!(q.pop(), 48); } #[test] fn push_pop_many_seq() { let q: MsQueue = MsQueue::new(); assert!(q.is_empty()); for i in 0..200 { q.push(i) } assert!(!q.is_empty()); for i in 0..200 { assert_eq!(q.pop(), i); } assert!(q.is_empty()); } #[test] fn push_try_pop_many_spsc() { let q: MsQueue = MsQueue::new(); assert!(q.is_empty()); scope(|scope| { scope.spawn(|| { let mut next = 0; while next < CONC_COUNT { if let Some(elem) = q.try_pop() { assert_eq!(elem, next); next += 1; } } }); for i in 0..CONC_COUNT { q.push(i) } }); } #[test] fn push_try_pop_many_spmc() { fn recv(_t: i32, q: &MsQueue) { let mut cur = -1; for _i in 0..CONC_COUNT { if let Some(elem) = q.try_pop() { assert!(elem > cur); cur = elem; if cur == CONC_COUNT - 1 { break } } } } let q: MsQueue = MsQueue::new(); assert!(q.is_empty()); let qr = &q; scope(|scope| { for i in 0..3 { scope.spawn(move || recv(i, qr)); } scope.spawn(|| { for i in 0..CONC_COUNT { q.push(i); } }) }); } #[test] fn push_try_pop_many_mpmc() { enum LR { Left(i64), Right(i64) } let q: MsQueue = MsQueue::new(); assert!(q.is_empty()); scope(|scope| { for _t in 0..2 { scope.spawn(|| { for i in CONC_COUNT-1..CONC_COUNT { q.push(LR::Left(i)) } }); scope.spawn(|| { for i in CONC_COUNT-1..CONC_COUNT { q.push(LR::Right(i)) } }); scope.spawn(|| { let mut vl = vec![]; let mut vr = vec![]; for _i in 0..CONC_COUNT { match q.try_pop() { Some(LR::Left(x)) => vl.push(x), Some(LR::Right(x)) => vr.push(x), _ => {} } } let mut vl2 = vl.clone(); let mut vr2 = vr.clone(); vl2.sort(); vr2.sort(); assert_eq!(vl, vl2); assert_eq!(vr, vr2); }); } }); } #[test] fn push_pop_many_spsc() { let q: MsQueue = MsQueue::new(); scope(|scope| { scope.spawn(|| { let mut next = 0; while next < CONC_COUNT { assert_eq!(q.pop(), next); next += 1; } }); for i in 0..CONC_COUNT { q.push(i) } }); assert!(q.is_empty()); } #[test] fn is_empty_dont_pop() { let q: MsQueue = MsQueue::new(); q.push(20); q.push(20); assert!(!q.is_empty()); assert!(!q.is_empty()); assert!(q.try_pop().is_some()); } } crossbeam-0.3.2/src/sync/seg_queue.rs010066400017510001751000000177551322354550400160340ustar0000000000000000use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::fmt; use std::{ptr, mem}; use std::cmp; use std::cell::UnsafeCell; use epoch::{self, Atomic, Owned}; const SEG_SIZE: usize = 32; /// A Michael-Scott queue that allocates "segments" (arrays of nodes) /// for efficiency. /// /// Usable with any number of producers and consumers. #[derive(Debug)] pub struct SegQueue { head: Atomic>, tail: Atomic>, } struct Segment { low: AtomicUsize, data: [UnsafeCell<(T, AtomicBool)>; SEG_SIZE], high: AtomicUsize, next: Atomic>, } impl fmt::Debug for Segment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Segment {{ ... }}") } } unsafe impl Sync for Segment {} impl Segment { fn new() -> Segment { let rqueue = Segment { data: unsafe { mem::uninitialized() }, low: AtomicUsize::new(0), high: AtomicUsize::new(0), next: Atomic::null(), }; for val in rqueue.data.iter() { unsafe { (*val.get()).1 = AtomicBool::new(false); } } rqueue } } impl SegQueue { /// Create a new, empty queue. pub fn new() -> SegQueue { let q = SegQueue { head: Atomic::null(), tail: Atomic::null(), }; let sentinel = Owned::new(Segment::new()); let guard = epoch::pin(); let sentinel = q.head.store_and_ref(sentinel, Relaxed, &guard); q.tail.store_shared(Some(sentinel), Relaxed); q } /// Add `t` to the back of the queue. pub fn push(&self, t: T) { let guard = epoch::pin(); loop { let tail = self.tail.load(Acquire, &guard).unwrap(); if tail.high.load(Relaxed) >= SEG_SIZE { continue } let i = tail.high.fetch_add(1, Relaxed); unsafe { if i < SEG_SIZE { let cell = (*tail).data.get_unchecked(i).get(); ptr::write(&mut (*cell).0, t); (*cell).1.store(true, Release); if i + 1 == SEG_SIZE { let tail = tail.next.store_and_ref(Owned::new(Segment::new()), Release, &guard); self.tail.store_shared(Some(tail), Release); } return } } } } /// Judge if the queue is empty. /// /// Returns `true` if the queue is empty. pub fn is_empty(&self) -> bool { let guard = epoch::pin(); let head = self.head.load(Acquire, &guard).unwrap(); let tail = self.tail.load(Acquire, &guard).unwrap(); if head.as_raw() != tail.as_raw() { return false; } let low = head.low.load(Relaxed); low >= cmp::min(head.high.load(Relaxed), SEG_SIZE) } /// Attempt to dequeue from the front. /// /// Returns `None` if the queue is observed to be empty. pub fn try_pop(&self) -> Option { let guard = epoch::pin(); loop { let head = self.head.load(Acquire, &guard).unwrap(); loop { let low = head.low.load(Relaxed); if low >= cmp::min(head.high.load(Relaxed), SEG_SIZE) { break } if head.low.compare_and_swap(low, low+1, Relaxed) == low { unsafe { let cell = (*head).data.get_unchecked(low).get(); loop { if (*cell).1.load(Acquire) { break } } if low + 1 == SEG_SIZE { loop { if let Some(next) = head.next.load(Acquire, &guard) { self.head.store_shared(Some(next), Release); guard.unlinked(head); break } } } return Some(ptr::read(&(*cell).0)) } } } if head.next.load(Relaxed, &guard).is_none() { return None } } } } impl Drop for SegQueue { fn drop(&mut self) { while self.try_pop().is_some() {} // Destroy the remaining sentinel segment. let guard = epoch::pin(); let sentinel = self.head.load(Relaxed, &guard).unwrap().as_raw(); unsafe { drop(Vec::from_raw_parts(sentinel, 0, 1)); } } } #[cfg(test)] mod test { const CONC_COUNT: i64 = 1000000; use scope; use super::*; #[test] fn push_pop_1() { let q: SegQueue = SegQueue::new(); q.push(37); assert_eq!(q.try_pop(), Some(37)); } #[test] fn push_pop_2() { let q: SegQueue = SegQueue::new(); q.push(37); q.push(48); assert_eq!(q.try_pop(), Some(37)); assert_eq!(q.try_pop(), Some(48)); } #[test] fn push_pop_empty_check() { let q: SegQueue = SegQueue::new(); assert_eq!(q.is_empty(), true); q.push(42); assert_eq!(q.is_empty(), false); assert_eq!(q.try_pop(), Some(42)); assert_eq!(q.is_empty(), true); } #[test] fn push_pop_many_seq() { let q: SegQueue = SegQueue::new(); for i in 0..200 { q.push(i) } for i in 0..200 { assert_eq!(q.try_pop(), Some(i)); } } #[test] fn push_pop_many_spsc() { let q: SegQueue = SegQueue::new(); scope(|scope| { scope.spawn(|| { let mut next = 0; while next < CONC_COUNT { if let Some(elem) = q.try_pop() { assert_eq!(elem, next); next += 1; } } }); for i in 0..CONC_COUNT { q.push(i) } }); } #[test] fn push_pop_many_spmc() { fn recv(_t: i32, q: &SegQueue) { let mut cur = -1; for _i in 0..CONC_COUNT { if let Some(elem) = q.try_pop() { assert!(elem > cur); cur = elem; if cur == CONC_COUNT - 1 { break } } } } let q: SegQueue = SegQueue::new(); let qr = &q; scope(|scope| { for i in 0..3 { scope.spawn(move || recv(i, qr)); } scope.spawn(|| { for i in 0..CONC_COUNT { q.push(i); } }) }); } #[test] fn push_pop_many_mpmc() { enum LR { Left(i64), Right(i64) } let q: SegQueue = SegQueue::new(); scope(|scope| { for _t in 0..2 { scope.spawn(|| { for i in CONC_COUNT-1..CONC_COUNT { q.push(LR::Left(i)) } }); scope.spawn(|| { for i in CONC_COUNT-1..CONC_COUNT { q.push(LR::Right(i)) } }); scope.spawn(|| { let mut vl = vec![]; let mut vr = vec![]; for _i in 0..CONC_COUNT { match q.try_pop() { Some(LR::Left(x)) => vl.push(x), Some(LR::Right(x)) => vr.push(x), _ => {} } } let mut vl2 = vl.clone(); let mut vr2 = vr.clone(); vl2.sort(); vr2.sort(); assert_eq!(vl, vl2); assert_eq!(vr, vr2); }); } }); } } crossbeam-0.3.2/src/sync/treiber_stack.rs010066400017510001751000000055641322354550400166660ustar0000000000000000use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; use std::ptr; use epoch::{self, Atomic, Owned}; /// Treiber's lock-free stack. /// /// Usable with any number of producers and consumers. #[derive(Debug)] pub struct TreiberStack { head: Atomic>, } #[derive(Debug)] struct Node { data: T, next: Atomic>, } impl TreiberStack { /// Create a new, empty stack. pub fn new() -> TreiberStack { TreiberStack { head: Atomic::null() } } /// Push `t` on top of the stack. pub fn push(&self, t: T) { let mut n = Owned::new(Node { data: t, next: Atomic::null(), }); let guard = epoch::pin(); loop { let head = self.head.load(Relaxed, &guard); n.next.store_shared(head, Relaxed); match self.head.cas_and_ref(head, n, Release, &guard) { Ok(_) => break, Err(owned) => n = owned, } } } /// Attempt to pop the top element of the stack. /// **Deprecated method**, use try_pop /// /// Returns `None` if the stack is observed to be empty. #[cfg_attr(any(feature="beta", feature="nightly"), deprecated(note="The pop method has been renamed to try_pop for consistency with other collections."))] pub fn pop(&self) -> Option { self.try_pop() } /// Attempt to pop the top element of the stack. /// /// Returns `None` if the stack is observed to be empty. pub fn try_pop(&self) -> Option { let guard = epoch::pin(); loop { match self.head.load(Acquire, &guard) { Some(head) => { let next = head.next.load(Relaxed, &guard); if self.head.cas_shared(Some(head), next, Release) { unsafe { guard.unlinked(head); return Some(ptr::read(&(*head).data)); } } } None => return None, } } } /// Check if this queue is empty. pub fn is_empty(&self) -> bool { let guard = epoch::pin(); self.head.load(Acquire, &guard).is_none() } } impl Drop for TreiberStack { fn drop(&mut self) { while self.try_pop().is_some() {} } } impl Default for TreiberStack { fn default() -> Self { TreiberStack::new() } } #[cfg(test)] mod test { use super::*; #[test] fn is_empty() { let q: TreiberStack = TreiberStack::new(); assert!(q.is_empty()); q.push(20); q.push(20); assert!(!q.is_empty()); assert!(!q.is_empty()); assert!(q.try_pop().is_some()); assert!(q.try_pop().is_some()); assert!(q.is_empty()); q.push(25); assert!(!q.is_empty()); } }