├── .gitignore ├── .travis.yml ├── Cargo.toml ├── examples └── order.rs ├── src ├── raw.rs └── lib.rs └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - nightly 4 | - stable 5 | cache: cargo 6 | 7 | script: 8 | - cargo build --verbose --all-features 9 | - cargo test --verbose --all-features 10 | - cargo build --verbose --no-default-features 11 | - cargo test --verbose --no-default-features 12 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ticketed_lock" 3 | version = "0.3.0" 4 | authors = ["Dzmitry Malyshau "] 5 | description = """ 6 | Ticketed lock system - allows one to separate lock request from the actual waiting. 7 | """ 8 | edition = "2018" 9 | documentation = "https://docs.rs/ticketed_lock/" 10 | repository = "https://github.com/kvark/ticketed_lock/" 11 | keywords = [] 12 | license = "Apache-2.0" 13 | exclude = ["doc", ".travis.yml"] 14 | 15 | [features] 16 | default = ["log"] 17 | 18 | [dependencies] 19 | log = { version = "0.4", optional = true } 20 | futures = { version = "0.3", optional = true } 21 | 22 | [[example]] 23 | name = "order" 24 | 25 | [dev-dependencies] 26 | env_logger = "0.8" 27 | -------------------------------------------------------------------------------- /examples/order.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use ticketed_lock as tl; 3 | 4 | fn main() { 5 | env_logger::init(); 6 | 7 | let mut storage = tl::TicketedLock::new(4u8); 8 | let t1 = storage.read(); 9 | let t2 = storage.read(); 10 | let t3 = storage.write(); 11 | 12 | let g3 = thread::spawn(move|| { 13 | let mut guard = t3.wait().expect("failed to wait on t3"); 14 | *guard += 1; 15 | println!("t3: {}", *guard); 16 | }); 17 | let g2 = thread::spawn(move|| { 18 | let guard = t2.wait().expect("failed to wait on t2"); 19 | println!("t2: {}", *guard); 20 | }); 21 | let g1 = thread::spawn(move|| { 22 | let guard = t1.wait().expect("failed to wait on t1"); 23 | println!("t1: {}", *guard); 24 | }); 25 | 26 | g1.join().unwrap(); 27 | g2.join().unwrap(); 28 | g3.join().unwrap(); 29 | } 30 | -------------------------------------------------------------------------------- /src/raw.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Arc, Condvar, Mutex, Weak}; 2 | #[cfg(feature = "futures")] 3 | use std::time::Duration; 4 | 5 | struct Link { 6 | cond_var: Condvar, 7 | mutex: Mutex, 8 | index: usize, 9 | } 10 | 11 | impl Link { 12 | #[cfg(feature = "log")] 13 | fn message(&self, info: &str) { 14 | debug!("link[{}] - {}", self.index, info); 15 | } 16 | #[cfg(not(feature = "log"))] 17 | fn message(&self, _: &str) { 18 | let _ = self.index; 19 | } 20 | } 21 | 22 | struct Seal { 23 | link: Arc, 24 | } 25 | 26 | impl Drop for Seal { 27 | fn drop(&mut self) { 28 | *self.link.mutex.lock().unwrap() = true; 29 | self.link.cond_var.notify_all(); 30 | } 31 | } 32 | 33 | type Legacy = Vec>; 34 | 35 | pub type Read = (); 36 | pub struct Write; 37 | 38 | #[derive(Clone)] 39 | pub struct Ticket { 40 | link: Arc, 41 | legacy: Arc>, 42 | access: A, 43 | } 44 | 45 | pub struct LockGuard { 46 | _legacy: Arc>, 47 | } 48 | 49 | impl Ticket { 50 | #[cfg(feature = "futures")] 51 | pub fn check(&mut self) -> Option { 52 | self.link.message("check"); 53 | let lock = self.link.mutex.lock().unwrap(); 54 | match self.link.cond_var.wait_timeout(lock, Duration::new(0, 0)) { 55 | Ok(_) => { 56 | self.link.message("acquired"); 57 | Some(LockGuard { 58 | _legacy: self.legacy.clone(), 59 | }) 60 | }, 61 | Err(_) => None, 62 | } 63 | } 64 | 65 | pub fn wait(self) -> LockGuard { 66 | self.link.message("wait"); 67 | // block until the seal is broken 68 | let mut lock = self.link.mutex.lock().unwrap(); 69 | while !*lock { 70 | lock = self.link.cond_var.wait(lock).unwrap(); 71 | } 72 | self.link.message("acquired"); 73 | // transform to a guard 74 | LockGuard { 75 | _legacy: self.legacy, 76 | } 77 | } 78 | } 79 | 80 | pub struct TicketedLock { 81 | next_index: usize, 82 | legacies: Vec>>, 83 | last_read: Option>, 84 | } 85 | 86 | impl TicketedLock { 87 | pub fn new() -> TicketedLock { 88 | TicketedLock { 89 | next_index: 0, 90 | legacies: Vec::new(), 91 | last_read: None, 92 | } 93 | } 94 | 95 | fn issue(&mut self) -> (Arc, Arc>) { 96 | // create a new link 97 | self.next_index += 1; 98 | let link = Arc::new(Link { 99 | cond_var: Condvar::new(), 100 | mutex: Mutex::new(false), 101 | index: self.next_index, 102 | }); 103 | // update all the existing legacies 104 | let seal = Arc::new(Seal { 105 | link: link.clone(), 106 | }); 107 | self.legacies.retain(|legacy| { 108 | match legacy.upgrade() { 109 | Some(leg) => { 110 | leg.lock().unwrap().push(seal.clone()); 111 | true 112 | }, 113 | None => false, 114 | } 115 | }); 116 | // add a new legacy 117 | let legacy = Arc::new(Mutex::new(Vec::new())); 118 | self.legacies.push(Arc::downgrade(&legacy)); 119 | // done 120 | (link, legacy) 121 | } 122 | 123 | pub fn write(&mut self) -> Ticket { 124 | self.last_read = None; 125 | let (link, legacy) = self.issue(); 126 | link.message("new write"); 127 | Ticket { 128 | link: link, 129 | legacy: legacy, 130 | access: Write, 131 | } 132 | } 133 | 134 | pub fn read(&mut self) -> Ticket { 135 | // check if there is already a read lock on top 136 | if let Some(ref ticket) = self.last_read { 137 | ticket.link.message("reread"); 138 | return ticket.clone(); 139 | } 140 | let (link, legacy) = self.issue(); 141 | link.message("new read"); 142 | Ticket { 143 | link: link, 144 | legacy: legacy, 145 | access: (), 146 | } 147 | } 148 | 149 | pub fn flush(&mut self) { 150 | //TODO 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | Ticketed lock. 3 | 4 | Ticketed lock is similar to RwLock, except that the acquisition of the lock is split: 5 | 6 | 1. obtaining a ticket, which has to be done on the same thread as the locked storage 7 | 2. waiting on a ticket, which puts the current thread to sleep until the ticket is due. That moment comes when all the previous tickets are processed. 8 | 3. working with the data behind a read/lock guard 9 | 4. when the guard is freed, it allows the following tickets to become active 10 | 11 | A ticket can be moved between threads or even just lost. 12 | Consecutive read-only tickets do not guarantee a particular lock order. 13 | All the ticket counting is done based on `Arc` primitives, and the only unsafe code that this library has is for accessing the actual data behind a guard. 14 | 15 | */ 16 | #![warn(missing_docs)] 17 | 18 | #[cfg(feature = "log")] 19 | #[macro_use] 20 | extern crate log; 21 | #[cfg(feature = "futures")] 22 | extern crate futures; 23 | 24 | mod raw; 25 | 26 | use std::{mem, ops}; 27 | use std::cell::UnsafeCell; 28 | use std::sync::Arc; 29 | #[cfg(feature = "futures")] 30 | use futures::{ 31 | Future, 32 | task::{Context, Poll}, 33 | }; 34 | #[cfg(feature = "futures")] 35 | use std::pin::Pin; 36 | 37 | 38 | /// The read-only guard of data, allowing `&T` dereferences. 39 | pub struct ReadLockGuard { 40 | _inner: raw::LockGuard, 41 | data: Arc>, 42 | } 43 | 44 | impl ops::Deref for ReadLockGuard { 45 | type Target = T; 46 | fn deref(&self) -> &T { 47 | unsafe{ mem::transmute(self.data.get()) } 48 | } 49 | } 50 | 51 | /// A ticket to read the data at some point. 52 | #[derive(Clone)] 53 | pub struct ReadTicket { 54 | inner: raw::Ticket, 55 | data: Arc>, 56 | } 57 | 58 | unsafe impl Send for ReadTicket {} 59 | 60 | impl ReadTicket { 61 | /// Wait for the ticket to become active, returning a lock guard. 62 | pub fn wait(self) -> Result, ()> { 63 | Ok(ReadLockGuard { 64 | _inner: self.inner.wait(), 65 | data: self.data, 66 | }) 67 | } 68 | } 69 | 70 | #[cfg(feature = "futures")] 71 | impl Future for ReadTicket { 72 | type Output = Result, ()>; 73 | 74 | fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll { 75 | match self.inner.check() { 76 | Some(guard) => Poll::Ready(Ok(ReadLockGuard { 77 | _inner: guard, 78 | data: self.data.clone(), 79 | })), 80 | None => Poll::Pending, 81 | } 82 | } 83 | } 84 | 85 | 86 | /// The read/write guard of data, allowing `&mut T` dereferences. 87 | pub struct WriteLockGuard { 88 | _inner: raw::LockGuard, 89 | data: Arc>, 90 | } 91 | 92 | impl ops::Deref for WriteLockGuard { 93 | type Target = T; 94 | fn deref(&self) -> &T { 95 | unsafe { mem::transmute(self.data.get()) } 96 | } 97 | } 98 | 99 | impl ops::DerefMut for WriteLockGuard { 100 | fn deref_mut(&mut self) -> &mut T { 101 | unsafe { mem::transmute(self.data.get()) } 102 | } 103 | } 104 | 105 | /// A ticket to read/write the data at some point. 106 | pub struct WriteTicket { 107 | inner: raw::Ticket, 108 | data: Arc>, 109 | } 110 | 111 | unsafe impl Send for WriteTicket {} 112 | 113 | impl WriteTicket { 114 | /// Wait for the ticket to become active, returning a lock guard. 115 | pub fn wait(self) -> Result, ()> { 116 | Ok(WriteLockGuard { 117 | _inner: self.inner.wait(), 118 | data: self.data, 119 | }) 120 | } 121 | } 122 | 123 | #[cfg(feature = "futures")] 124 | impl Future for WriteTicket { 125 | type Output = Result, ()>; 126 | 127 | fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll { 128 | match self.inner.check() { 129 | Some(guard) => Poll::Ready(Ok(WriteLockGuard { 130 | _inner: guard, 131 | data: self.data.clone(), 132 | })), 133 | None => Poll::Pending, 134 | } 135 | } 136 | } 137 | 138 | 139 | /// The ticketed lock, which wraps the data. 140 | pub struct TicketedLock { 141 | inner: raw::TicketedLock, 142 | data: Arc>, 143 | } 144 | 145 | unsafe impl Send for TicketedLock {} 146 | unsafe impl Sync for TicketedLock {} 147 | 148 | impl TicketedLock { 149 | /// Create a new ticketed lock. 150 | pub fn new(data: T) -> TicketedLock { 151 | TicketedLock { 152 | inner: raw::TicketedLock::new(), 153 | data: Arc::new(UnsafeCell::new(data)), 154 | } 155 | } 156 | 157 | /// Remove the lock and extract the data out. 158 | pub fn unlock(mut self) -> T { 159 | self.inner.flush(); 160 | match Arc::try_unwrap(self.data) { 161 | Ok(data) => data.into_inner(), 162 | Err(_) => panic!("All the locks are supposed to be done after flush()"), 163 | } 164 | } 165 | 166 | /// Acquire a read-only ticket. 167 | pub fn read(&mut self) -> ReadTicket { 168 | ReadTicket { 169 | inner: self.inner.read(), 170 | data: self.data.clone(), 171 | } 172 | } 173 | 174 | /// Acquire a read/write ticket. 175 | pub fn write(&mut self) -> WriteTicket { 176 | WriteTicket { 177 | inner: self.inner.write(), 178 | data: self.data.clone(), 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------