spinning-0.1.0/.cargo_vcs_info.json0000644000000001120000000000000126500ustar { "git": { "sha1": "71ab2cbc4d5283f8dceef46da58f2630d40fd16a" } } spinning-0.1.0/.github/workflows/rust.yml000064400000000000000000000005250000000000000165430ustar 00000000000000name: Rust on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run fmt run: cargo fmt --all -- --check - name: Build run: cargo build --verbose - name: Run tests run: cargo test --verbose spinning-0.1.0/.gitignore000064400000000000000000000000230000000000000134070ustar 00000000000000/target Cargo.lock spinning-0.1.0/.travis.yml000064400000000000000000000003230000000000000135330ustar 00000000000000language: rust rust: - stable - beta - nightly script: - cargo build --verbose --all - cargo test --verbose --all arch: - amd64 - arm64 - ppc64le jobs: allow_failures: fast_finish: true spinning-0.1.0/Cargo.toml0000644000000021310000000000000106510ustar # 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] edition = "2018" name = "spinning" version = "0.1.0" authors = ["4lDO2 <4lDO2@protonmail.com>"] exclude = ["target"] description = "Mutexes and SIX locks implemented by spinning" documentation = "https://docs.rs/spinning" readme = "README.md" keywords = ["rwlock", "mutex", "spinlock", "no_std", "once"] categories = ["concurrency", "no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/4lDO2/spinning-rs.git" [dependencies.lock_api] version = "0.4" [features] default = ["std"] std = [] [badges.travis-ci] branch = "master" repository = "4lDO2/spinning-rs" spinning-0.1.0/Cargo.toml.orig000064400000000000000000000012570000000000000143200ustar 00000000000000[package] name = "spinning" version = "0.1.0" authors = ["4lDO2 <4lDO2@protonmail.com>"] edition = "2018" description = "Mutexes and SIX locks implemented by spinning" documentation = "https://docs.rs/spinning" readme = "README.md" repository = "https://github.com/4lDO2/spinning-rs.git" license = "MIT OR Apache-2.0" keywords = ["rwlock", "mutex", "spinlock", "no_std", "once"] categories = ["concurrency", "no-std"] exclude = ["target"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] default = ["std"] std = [] [badges] travis-ci = { repository = "4lDO2/spinning-rs", branch = "master" } [dependencies] lock_api = "0.4" spinning-0.1.0/LICENSE-APACHE000064400000000000000000000261350000000000000133570ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. spinning-0.1.0/LICENSE-MIT000064400000000000000000000020460000000000000130620ustar 00000000000000MIT License Copyright (c) 2020 4lDO2 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. spinning-0.1.0/README.md000064400000000000000000000020340000000000000127020ustar 00000000000000# spinning-rs [![Build Status](https://travis-ci.org/4lDO2/spinning-rs.svg?branch=master)](https://travis-ci.org/4lDO2/spinning-rs) [![Crates.io](https://img.shields.io/crates/v/spinning.svg)](https://crates.io/crates/spinning) [![Documentation](https://docs.rs/spinning/badge.svg)](https://docs.rs/spinning/) A `#![no_std]` crate for spinlocks, intended to function similarly to [`spin`](https://crates.io/crates/spin), but with enhanced features such as SIX (shared-intent-exclusive) rwlocks, and [`lock_api`](https://crates.io/crates/lock_api). ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. spinning-0.1.0/rustfmt.toml000064400000000000000000000000000000000000000140130ustar 00000000000000spinning-0.1.0/src/lib.rs000064400000000000000000000704200000000000000133320ustar 00000000000000#![cfg_attr(all(not(test), not(feature = "std")), no_std)] use core::cell::{Cell, UnsafeCell}; use core::fmt; use core::mem::{self, MaybeUninit}; use core::ops::Deref; use core::ptr; use core::sync::atomic::{self, AtomicBool, AtomicU8, AtomicUsize, Ordering}; /// An extremely simple spinlock, locking by compare-and-swapping a single flag and repeating. pub struct RawMutex { locked: AtomicBool, } impl RawMutex { pub const fn const_new() -> Self { RawMutex { locked: AtomicBool::new(false), } } } unsafe impl lock_api::RawMutex for RawMutex { const INIT: Self = RawMutex::const_new(); type GuardMarker = lock_api::GuardNoSend; fn lock(&self) { while !self.try_lock() { atomic::spin_loop_hint(); } } fn try_lock(&self) -> bool { self.locked .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) .is_ok() } unsafe fn unlock(&self) { let prev = self.locked.fetch_and(false, Ordering::Release); debug_assert!(prev, "unlocking when not locked"); } } #[derive(Debug)] pub struct RawRwLock { // The state of the rwlock is composed as follows: // // 1. The base bits, all the way up to ARCH_POINTER_WIDTH - 4, are used to count the number of // current locks. These also include the one occasional intent or write lock, and the reason // for this is to allow for more simple atomic operations, since x86 has no instrucion doing // both bit tests and addition. // 2. RWLOCK_STATE_ACTIVE_WRITER_BIT indicates that the lock currently holds a writer. When // acquiring a shared lock, the counter may be incremented arbitrarily, but acquiring a // shared lock must always fail when this bit is set. // 3. RWLOCK_STATE_ACTIVE_INTENT_BIT denotes that the rwlock currently holds an intent lock. // Attaining a shared lock does ignores this bit, since intent locks only conflict with write // locks, until they are upgraded to write locks. // 4. RWLOCK_STATE_PENDING_WRITER_BIT can be set at any time by a failed attempt at obtaining a // write lock, due to shared locks already being present. In order to prevent write lock // starvation, new shared locks cannot be acquired if this bit is set. state: AtomicUsize, } impl Clone for RawRwLock { fn clone(&self) -> Self { Self { state: AtomicUsize::new(0), } } } const RWLOCK_STATE_ACTIVE_WRITER_BIT: usize = 1 << (mem::size_of::() * 8 - 1); const RWLOCK_STATE_ACTIVE_INTENT_BIT: usize = 1 << (mem::size_of::() * 8 - 2); const RWLOCK_STATE_PENDING_WRITER_BIT: usize = 1 << (mem::size_of::() * 8 - 3); const RWLOCK_STATE_EXTRA_MASK: usize = RWLOCK_STATE_ACTIVE_WRITER_BIT | RWLOCK_STATE_ACTIVE_INTENT_BIT | RWLOCK_STATE_PENDING_WRITER_BIT; const RWLOCK_STATE_COUNT_MASK: usize = !RWLOCK_STATE_EXTRA_MASK; impl RawRwLock { pub const fn const_new() -> Self { RawRwLock { state: AtomicUsize::new(0), } } fn try_lock_exclusive_raw(&self) -> (bool, bool) { let prev_state = self .state .fetch_or(RWLOCK_STATE_PENDING_WRITER_BIT, Ordering::AcqRel); let current_state = prev_state | RWLOCK_STATE_PENDING_WRITER_BIT; let was_previously_pending = prev_state & RWLOCK_STATE_PENDING_WRITER_BIT != 0; if prev_state & RWLOCK_STATE_ACTIVE_INTENT_BIT != 0 { debug_assert_eq!(prev_state & RWLOCK_STATE_ACTIVE_WRITER_BIT, 0, "simultaneously active INTENT and exclusive locks during exclusive lock acquisition"); return (false, was_previously_pending); } if prev_state & RWLOCK_STATE_ACTIVE_WRITER_BIT != 0 { debug_assert_eq!(prev_state & RWLOCK_STATE_ACTIVE_INTENT_BIT, 0, "simultaneously active intent and EXCLUSIVE locks during exclusive lock acquisition"); return (false, was_previously_pending); } let success = self .state .compare_exchange( current_state, (current_state + 1) | RWLOCK_STATE_ACTIVE_WRITER_BIT, // make sure that the lock is updated to be an exclusive lock, before any // subsequent operations assume that underlying data to be readable (success // ordering). Ordering::Acquire, // a failed attempt to attain an exclusive lock means that the lock cannot later be // used for data accesses, and thus no synchronization is needed here (failure // ordering). Ordering::Relaxed, ) .is_ok(); (success, was_previously_pending) } unsafe fn try_upgrade_raw(&self) -> (bool, bool) { let prev = self .state .fetch_or(RWLOCK_STATE_PENDING_WRITER_BIT, Ordering::Relaxed); debug_assert_ne!( prev & RWLOCK_STATE_ACTIVE_INTENT_BIT, 0, "upgrading an intent lock into an exclusive lock when no intent lock was held" ); let was_previously_pending = prev & RWLOCK_STATE_PENDING_WRITER_BIT != 0; let prev = self.state.compare_exchange_weak( RWLOCK_STATE_ACTIVE_INTENT_BIT | RWLOCK_STATE_PENDING_WRITER_BIT | 1, RWLOCK_STATE_ACTIVE_WRITER_BIT | 1, // make sure that the no operations that rely on the lock being an exclusive lock, // happen *after* the lock has been marked exclusive (success ordering). Ordering::Acquire, // no synchronization needs to happen, since a lock is neither obtained nor released // (failure ordering). Ordering::Relaxed, ); if let Ok(prev_raw) = prev { debug_assert_eq!( prev_raw & RWLOCK_STATE_ACTIVE_WRITER_BIT, 0, "upgrading an intent lock into an exclusive lock when an exclusive lock was held" ); } (prev.is_ok(), was_previously_pending) } } unsafe impl lock_api::RawRwLock for RawRwLock { const INIT: Self = RawRwLock::const_new(); type GuardMarker = lock_api::GuardNoSend; fn lock_shared(&self) { while !self.try_lock_shared() { atomic::spin_loop_hint(); } } fn try_lock_shared(&self) -> bool { let prev = self.state.fetch_add(1, Ordering::Acquire); if prev & RWLOCK_STATE_PENDING_WRITER_BIT != 0 { // don't starve writers; writers are prioritized over readers return false; } if prev & RWLOCK_STATE_ACTIVE_WRITER_BIT != 0 { let new_prev = self.state.fetch_sub(1, Ordering::Release); debug_assert_ne!( new_prev & !(RWLOCK_STATE_ACTIVE_WRITER_BIT | RWLOCK_STATE_ACTIVE_INTENT_BIT), 0, "overflow when subtracting rwlock counter" ); return false; } true } fn lock_exclusive(&self) { while !self.try_lock_exclusive() { atomic::spin_loop_hint(); } } fn try_lock_exclusive(&self) -> bool { let (success, was_previously_pending) = self.try_lock_exclusive_raw(); if success && !was_previously_pending { self.state .fetch_and(!RWLOCK_STATE_PENDING_WRITER_BIT, Ordering::Relaxed); } success } // releases a shared lock unsafe fn unlock_shared(&self) { let prev = self.state.fetch_sub(1, Ordering::Release); debug_assert_ne!( prev & RWLOCK_STATE_COUNT_MASK, 0, "corrupted state flags because of subtraction overflow, when release a shared lock" ); debug_assert_eq!( prev & RWLOCK_STATE_ACTIVE_WRITER_BIT, 0, "releasing a shared lock while an exclusive lock was held" ); } // releases an exclusive lock unsafe fn unlock_exclusive(&self) { let prev = self .state .fetch_sub(RWLOCK_STATE_ACTIVE_WRITER_BIT | 1, Ordering::Release); debug_assert_ne!(prev & RWLOCK_STATE_ACTIVE_WRITER_BIT, 0, "corrupted state flags because an exclusive lock release was tried when an exclusive lock was not held"); debug_assert_eq!( prev & RWLOCK_STATE_ACTIVE_INTENT_BIT, 0, "releasing an exclusive lock when an intent lock was held" ); } } unsafe impl lock_api::RawRwLockDowngrade for RawRwLock { // downgrades an exclusive lock to a shared lock unsafe fn downgrade(&self) { let prev = self .state .fetch_and(!RWLOCK_STATE_ACTIVE_WRITER_BIT, Ordering::Release); debug_assert_ne!( prev & RWLOCK_STATE_ACTIVE_WRITER_BIT, 0, "downgrading an exclusive lock to a shared lock when no exclusive lock was held" ); debug_assert_eq!( prev & RWLOCK_STATE_ACTIVE_INTENT_BIT, 0, "downgrading a exclusive lock to a shared lock when an intent lock was held" ); } } unsafe impl lock_api::RawRwLockUpgrade for RawRwLock { // acquires an intent lock fn lock_upgradable(&self) { while !self.try_lock_upgradable() { atomic::spin_loop_hint(); } } // tries to acquire an intent lock fn try_lock_upgradable(&self) -> bool { use lock_api::RawRwLock as _; // Begin by acquiring a shared lock. if !self.try_lock_shared() { return false; }; // At this stage we know that it is completely impossible for a exclusive lock to exist, since // try_lock_shared() would return false in that case. Hence, all we have to do is setting // the active intent bit, and returning false if it was already set. let prev = self .state .fetch_or(RWLOCK_STATE_ACTIVE_INTENT_BIT, Ordering::AcqRel); debug_assert_eq!( prev & RWLOCK_STATE_ACTIVE_WRITER_BIT, 0, "acquiring an intent lock while an exclusive lock was held" ); prev & RWLOCK_STATE_ACTIVE_INTENT_BIT == 0 } // releases an intent lock unsafe fn unlock_upgradable(&self) { // assumes that the lock is properly managed by lock_api; if RWLOCK_STATE_ACTIVE_INTENT_BIT // is not set and this method is called, the CPU will arithmetically borrow the bits below, // potentially corrupting the rwlock state entirely. let prev = self .state .fetch_sub(RWLOCK_STATE_ACTIVE_INTENT_BIT | 1, Ordering::Release); debug_assert_ne!( prev & RWLOCK_STATE_ACTIVE_INTENT_BIT, 0, "releasing an intent lock while no intent lock was held" ); debug_assert_eq!( prev & RWLOCK_STATE_ACTIVE_WRITER_BIT, 0, "releasing an intent lock while an exclusive lock was held" ); } // upgrades an intent lock into an exclusive lock unsafe fn upgrade(&self) { while !self.try_upgrade() { atomic::spin_loop_hint(); } } // tries to upgrade an intent lock into an exclusive lock unsafe fn try_upgrade(&self) -> bool { let (success, was_previously_pending) = self.try_upgrade_raw(); if success && !was_previously_pending { self.state .fetch_and(!RWLOCK_STATE_PENDING_WRITER_BIT, Ordering::Relaxed); } success } } unsafe impl lock_api::RawRwLockUpgradeDowngrade for RawRwLock { // downgrades an exclusive lock to an intent lock unsafe fn downgrade_to_upgradable(&self) { let prev = self.state.fetch_xor( RWLOCK_STATE_ACTIVE_WRITER_BIT | RWLOCK_STATE_ACTIVE_INTENT_BIT, // ensure that previous memory accesses, which may have been writes (as we are // downgrading an exclusive lock), happen before other threads see this downgrade. Ordering::Release, ); debug_assert_ne!( prev & RWLOCK_STATE_ACTIVE_WRITER_BIT, 0, "downgrading a exclusive lock to an intent lock when no exclusive lock was held" ); debug_assert_eq!( prev & RWLOCK_STATE_ACTIVE_INTENT_BIT, 0, "downgrading a exclusive lock to an intent lock when an intent lock was held" ); } // downgrades an intent lock into a shared lock unsafe fn downgrade_upgradable(&self) { let prev = self.state.fetch_and( !RWLOCK_STATE_ACTIVE_INTENT_BIT, // this ordering is correct, because no memory accesses that may have happened // before, or are going to happen afterwards, will have different rules regarding // mutability (intent locks are only shared locks but with the exception that there // can only be one intent lock at a time). Ordering::Relaxed, ); debug_assert_eq!( prev & RWLOCK_STATE_ACTIVE_WRITER_BIT, 0, "downgrading an intent lock while a exclusive lock was held" ); debug_assert_ne!( prev & RWLOCK_STATE_ACTIVE_INTENT_BIT, 0, "downgrading an intent lock where no intent lock was held" ); } } pub type Mutex = lock_api::Mutex; pub type MutexGuard<'a, T> = lock_api::MutexGuard<'a, RawMutex, T>; pub type MappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawMutex, T>; pub type RwLock = lock_api::RwLock; pub type RwLockReadGuard<'a, T> = lock_api::RwLockReadGuard<'a, RawRwLock, T>; pub type RwLockWriteGuard<'a, T> = lock_api::RwLockWriteGuard<'a, RawRwLock, T>; pub type RwLockUpgradableReadGuard<'a, T> = lock_api::RwLockUpgradableReadGuard<'a, RawRwLock, T>; pub type MappedRwLockReadGuard<'a, T> = lock_api::MappedRwLockReadGuard<'a, RawRwLock, T>; pub type MappedRwLockWriteGuard<'a, T> = lock_api::MappedRwLockWriteGuard<'a, RawRwLock, T>; pub type ReentrantMutex = lock_api::ReentrantMutex; pub type ReentrantMutexGuard<'a, T, G> = lock_api::ReentrantMutexGuard<'a, RawRwLock, G, T>; /// A synchronization primitive which initializes a value lazily, once. Since this also includes a /// value, it is a bit more like `Once` from `parking_lot` or `spin`. #[derive(Debug)] pub struct Once { state: AtomicU8, value: UnsafeCell>, } impl Drop for Once { fn drop(&mut self) { // we do not have to do any complex state manipulation here, since a mutable reference // guarantees that only there is an exclusive borrow to this struct. if *self.state.get_mut() != OnceState::Initialized as u8 { // nothing to drop return; } unsafe { ptr::drop_in_place(self.value.get() as *mut T) } } } unsafe impl Send for Once {} unsafe impl Sync for Once {} #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum OnceState { Uninitialized = 0, Initializing = 1, Initialized = 2, } impl Once { pub const fn new() -> Self { Self { state: AtomicU8::new(OnceState::Uninitialized as u8), value: UnsafeCell::new(MaybeUninit::uninit()), } } pub const fn uninitialized() -> Self { Self::new() } pub const fn initialized(value: T) -> Self { Self { state: AtomicU8::new(OnceState::Initialized as u8), value: UnsafeCell::new(MaybeUninit::new(value)), } } pub fn initialize(&self, value: T) -> Result<(), T> { match self.state.compare_exchange( OnceState::Uninitialized as u8, OnceState::Initializing as u8, // make sure that the actual pointer store must happen after other threads have seen // the updated state (success ordering). Ordering::Acquire, // if the once was not uninitialized, there will not be any additional stores, and // since we just return upon failure, Relaxed suffices here. Ordering::Relaxed, ) { Ok(_) => { unsafe { (*self.value.get()).as_mut_ptr().write(value); }; let old = self .state .swap(OnceState::Initialized as u8, Ordering::Release); debug_assert_eq!( old, OnceState::Initializing as u8, "once state was modified when setting state to \"initialized\"" ); Ok(()) } Err(_) => Err(value), } } pub fn try_call_once<'a, F>(&'a self, init: F) -> Result<&'a T, F> where F: FnOnce() -> T, { match self.state.compare_exchange( OnceState::Uninitialized as u8, OnceState::Initializing as u8, Ordering::Acquire, Ordering::Relaxed, ) { Ok(_) => unsafe { (*self.value.get()).as_mut_ptr().write(init()); let old = self .state .swap(OnceState::Initialized as u8, Ordering::Release); debug_assert_eq!( old, OnceState::Initializing as u8, "once state was modified when setting state to \"initialized\"" ); Ok(&*((*self.value.get()).as_ptr())) }, Err(other_state) if other_state == OnceState::Initialized as u8 => unsafe { Ok(&*((*self.value.get()).as_ptr())) }, #[cfg(debug_assertions)] Err(other_state) if other_state == OnceState::Initializing as u8 => Err(init), #[cfg(debug_assertions)] Err(_) => unreachable!(), #[cfg(not(debug_assertions))] Err(_) => Err(init), } } pub fn call_once<'a, F>(&'a self, mut init: F) -> &'a T where F: FnOnce() -> T, { loop { match self.try_call_once(init) { Ok(reference) => return reference, Err(init_again) => { init = init_again; continue; } } } } pub fn wait<'a>(&'a self) -> &'a T { loop { match self.try_get() { Some(t) => return t, None => continue, } } } pub fn try_get<'a>(&'a self) -> Option<&'a T> { let state = self.state.load(Ordering::Acquire); if state != OnceState::Initialized as u8 { return None; } Some(unsafe { &*(self.value.get() as *const T) }) } pub fn state(&self) -> OnceState { match self.state.load(Ordering::Acquire) { 0 => OnceState::Uninitialized, 1 => OnceState::Initializing, 2 => OnceState::Initialized, _ => unreachable!(), } } } #[cfg(any(test, feature = "std"))] impl std::panic::UnwindSafe for Once {} #[cfg(any(test, feature = "std"))] impl std::panic::RefUnwindSafe for Once {} /// A value which is initialized on the first access. /// /// This type is thread-safe and can be used in statics. /// /// # Example /// /// ``` /// use std::collections::HashMap; /// /// use spinning::Lazy; /// /// static HASHMAP: Lazy> = Lazy::new(|| { /// println!("initializing"); /// let mut m = HashMap::new(); /// m.insert(13, "Spica".to_string()); /// m.insert(74, "Hoyten".to_string()); /// m /// }); /// /// fn main() { /// println!("ready"); /// std::thread::spawn(|| { /// println!("{:?}", HASHMAP.get(&13)); /// }).join().unwrap(); /// println!("{:?}", HASHMAP.get(&74)); /// /// // Prints: /// // ready /// // initializing /// // Some("Spica") /// // Some("Hoyten") /// } /// ``` pub struct Lazy T> { once: Once, init: Cell>, } impl fmt::Debug for Lazy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Lazy") .field("once", &self.once) .field("init", &"..") .finish() } } // We never create a `&F` from a `&Lazy` so it is fine // to not impl `Sync` for `F` // we do create a `&mut Option` in `force`, but this is // properly synchronized, so it only happens once // so it also does not contribute to this impl. unsafe impl Sync for Lazy where Once: Sync {} // auto-derived `Send` impl is OK. #[cfg(any(test, feature = "std"))] impl std::panic::RefUnwindSafe for Lazy where Once: std::panic::RefUnwindSafe { } impl Lazy { /// Creates a new lazy value with the given initializing /// function. pub const fn new(f: F) -> Lazy { Lazy { once: Once::new(), init: Cell::new(Some(f)), } } } impl T> Lazy { /// Forces the evaluation of this lazy value and /// returns a reference to the result. This is equivalent /// to the `Deref` impl, but is explicit. /// /// # Example /// ``` /// use spinning::Lazy; /// /// let lazy = Lazy::new(|| 92); /// /// assert_eq!(Lazy::force(&lazy), &92); /// assert_eq!(&*lazy, &92); /// ``` pub fn force(this: &Lazy) -> &T { this.once.call_once(|| match this.init.take() { Some(f) => f(), None => panic!("Lazy instance has previously been poisoned"), }) } } impl T> Deref for Lazy { type Target = T; fn deref(&self) -> &T { Lazy::force(self) } } impl Default for Lazy { /// Creates a new lazy value using `Default` as the initializing function. fn default() -> Lazy { Lazy::new(T::default) } } #[cfg(test)] mod tests { use super::{ Mutex, Once, OnceState, RawMutex, RawRwLock, RwLock, RwLockUpgradableReadGuard, RwLockWriteGuard, }; use std::{sync::Arc, thread}; #[test] fn singlethread_mutex() { let data = Mutex::new(2); assert_eq!(*data.lock(), 2); *data.lock() = 3; assert_eq!(*data.lock(), 3); } #[test] fn multithread_mutex() { let data = Arc::new(Mutex::new(2)); let main_thread = thread::current(); assert_eq!(*data.lock(), 2); { let data = Arc::clone(&data); thread::spawn(move || { *data.lock() = 3; main_thread.unpark(); }); } thread::park(); assert_eq!(*data.lock(), 3); } #[test] fn multithread_rwlock() { // TODO: More complex test, or maybe this is done in an integration test. let data = Arc::new(RwLock::new(Vec::::new())); assert_eq!(&*data.read(), &[]); let threads = (0..4) .map(|index| { let data = Arc::clone(&data); thread::spawn(move || { let mut write_guard = data.write(); write_guard.push(index); }) }) .collect::>(); for thread in threads { thread.join().unwrap(); } let mut write_guard = data.write(); write_guard.sort(); let read_guard = RwLockWriteGuard::downgrade(write_guard); assert_eq!(&*read_guard, &[0, 1, 2, 3]); } #[test] fn singlethread_rwlock() { let data = RwLock::new(1); let intent_lock = data.upgradable_read(); { let lock1 = data.read(); let lock2 = data.read(); let lock3 = data.read(); assert_eq!(*lock1, 1); assert_eq!(*lock2, 1); assert_eq!(*lock3, 1); assert_eq!(*intent_lock, 1); } let mut write_lock = RwLockUpgradableReadGuard::upgrade(intent_lock); *write_lock = 2; let intent_lock_again = RwLockWriteGuard::downgrade_to_upgradable(write_lock); let lock1 = { let lock1 = data.read(); let lock2 = data.read(); assert_eq!(*intent_lock_again, 2); assert_eq!(*lock1, 2); assert_eq!(*lock2, 2); lock1 }; assert!(data.try_write().is_none()); let lock3 = RwLockUpgradableReadGuard::downgrade(intent_lock_again); assert_eq!(*lock3, 2); assert_eq!(*lock1, 2); } #[test] fn intent_upgrade() { let data = RwLock::new(7); let upgradable = { let lock1 = data.try_read().unwrap(); let lock2 = data.try_read().unwrap(); let lock3 = data.try_read().unwrap(); let upgradable = data.try_upgradable_read().unwrap(); let upgrade_result = RwLockUpgradableReadGuard::try_upgrade(upgradable); assert!( upgrade_result.is_err(), "upgraded intent lock into exclusive lock while there were still readers" ); assert_eq!(*lock1, 7); assert_eq!(*lock2, 7); assert_eq!(*lock3, 7); upgrade_result.err().unwrap() }; let mut write_lock = RwLockUpgradableReadGuard::try_upgrade(upgradable).unwrap(); *write_lock = 8; assert_eq!(*write_lock, 8); } #[test] fn singlethread_once() { let once = Once::::uninitialized(); assert_eq!(once.state(), OnceState::Uninitialized); assert_eq!(once.try_get(), None); once.initialize(String::from("Hello, world!")) .expect("once initialization failed"); assert_eq!(once.state(), OnceState::Initialized); assert_eq!(once.try_get().map(String::as_str), Some("Hello, world!")); assert_eq!(once.wait(), "Hello, world!"); assert!(once.initialize(String::from("Goodbye, world!")).is_err()); } #[test] fn once_preinit() { let once = Once::::initialized(String::from("Already initialized!")); assert_eq!(once.state(), OnceState::Initialized); assert_eq!( once.try_get().map(String::as_str), Some("Already initialized!") ); assert_eq!(once.wait(), "Already initialized!"); } #[test] fn once_with_panic_in_init() { let opinion = Arc::new(Once::::new()); let byte_str = b"Panicking is particul\xFFrly dangerous when dealing with unsafe!"; let opinion_clone = Arc::clone(&opinion); // set panic hook to avoid messing up stdout std::panic::set_hook(Box::new(|_| {})); let join_handle = thread::Builder::new() .name(String::from("this thread should panic")) .spawn(move || { opinion_clone.call_once(|| String::from_utf8(byte_str.to_vec()).unwrap()); }) .unwrap(); assert!(join_handle.join().is_err()); assert_eq!(opinion.try_get(), None); assert_eq!(opinion.state(), OnceState::Initializing); } #[test] fn multithread_once() { let once = Arc::new(Once::new()); assert_eq!(once.try_get(), None); assert_eq!(once.state(), OnceState::Uninitialized); let main_thread = thread::current(); let values = [ "initialized by first thread", "initialized by second thread", "initialized by third thread", ]; let threads = values .iter() .copied() .map(|value| { let once = Arc::clone(&once); let main_thread = main_thread.clone(); thread::spawn(move || { once.call_once(|| value); main_thread.unpark(); }) }) .collect::>(); thread::park(); assert!(once.initialize("initialized by main thread").is_err()); assert!(once.try_get().is_some()); assert!(values.contains(&once.wait())); for thread in threads { thread.join().unwrap(); } } #[test] fn const_init() { static mut _RWLOCK: RwLock = RwLock::const_new(RawRwLock::const_new(), 1); static mut _MUTEX: Mutex = Mutex::const_new(RawMutex::const_new(), 1); } // TODO: loom, although it doesn't seem to support const fn initialization }