]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/mpsc/mpsc_queue.rs
Rollup merge of #35962 - regexident:compiler-plugin-docs, r=steveklabnik
[rust.git] / src / libstd / sync / mpsc / mpsc_queue.rs
1 /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
2  * Redistribution and use in source and binary forms, with or without
3  * modification, are permitted provided that the following conditions are met:
4  *
5  *    1. Redistributions of source code must retain the above copyright notice,
6  *       this list of conditions and the following disclaimer.
7  *
8  *    2. Redistributions in binary form must reproduce the above copyright
9  *       notice, this list of conditions and the following disclaimer in the
10  *       documentation and/or other materials provided with the distribution.
11  *
12  * THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "AS IS" AND ANY EXPRESS OR IMPLIED
13  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
15  * SHALL DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
16  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
17  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
18  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
19  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
20  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
21  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22  *
23  * The views and conclusions contained in the software and documentation are
24  * those of the authors and should not be interpreted as representing official
25  * policies, either expressed or implied, of Dmitry Vyukov.
26  */
27
28 //! A mostly lock-free multi-producer, single consumer queue.
29 //!
30 //! This module contains an implementation of a concurrent MPSC queue. This
31 //! queue can be used to share data between threads, and is also used as the
32 //! building block of channels in rust.
33 //!
34 //! Note that the current implementation of this queue has a caveat of the `pop`
35 //! method, and see the method for more information about it. Due to this
36 //! caveat, this queue may not be appropriate for all use-cases.
37
38 // http://www.1024cores.net/home/lock-free-algorithms
39 //                         /queues/non-intrusive-mpsc-node-based-queue
40
41 pub use self::PopResult::*;
42
43 use alloc::boxed::Box;
44 use core::ptr;
45 use core::cell::UnsafeCell;
46
47 use sync::atomic::{AtomicPtr, Ordering};
48
49 /// A result of the `pop` function.
50 pub enum PopResult<T> {
51     /// Some data has been popped
52     Data(T),
53     /// The queue is empty
54     Empty,
55     /// The queue is in an inconsistent state. Popping data should succeed, but
56     /// some pushers have yet to make enough progress in order allow a pop to
57     /// succeed. It is recommended that a pop() occur "in the near future" in
58     /// order to see if the sender has made progress or not
59     Inconsistent,
60 }
61
62 struct Node<T> {
63     next: AtomicPtr<Node<T>>,
64     value: Option<T>,
65 }
66
67 /// The multi-producer single-consumer structure. This is not cloneable, but it
68 /// may be safely shared so long as it is guaranteed that there is only one
69 /// popper at a time (many pushers are allowed).
70 pub struct Queue<T> {
71     head: AtomicPtr<Node<T>>,
72     tail: UnsafeCell<*mut Node<T>>,
73 }
74
75 unsafe impl<T: Send> Send for Queue<T> { }
76 unsafe impl<T: Send> Sync for Queue<T> { }
77
78 impl<T> Node<T> {
79     unsafe fn new(v: Option<T>) -> *mut Node<T> {
80         Box::into_raw(box Node {
81             next: AtomicPtr::new(ptr::null_mut()),
82             value: v,
83         })
84     }
85 }
86
87 impl<T> Queue<T> {
88     /// Creates a new queue that is safe to share among multiple producers and
89     /// one consumer.
90     pub fn new() -> Queue<T> {
91         let stub = unsafe { Node::new(None) };
92         Queue {
93             head: AtomicPtr::new(stub),
94             tail: UnsafeCell::new(stub),
95         }
96     }
97
98     /// Pushes a new value onto this queue.
99     pub fn push(&self, t: T) {
100         unsafe {
101             let n = Node::new(Some(t));
102             let prev = self.head.swap(n, Ordering::AcqRel);
103             (*prev).next.store(n, Ordering::Release);
104         }
105     }
106
107     /// Pops some data from this queue.
108     ///
109     /// Note that the current implementation means that this function cannot
110     /// return `Option<T>`. It is possible for this queue to be in an
111     /// inconsistent state where many pushes have succeeded and completely
112     /// finished, but pops cannot return `Some(t)`. This inconsistent state
113     /// happens when a pusher is pre-empted at an inopportune moment.
114     ///
115     /// This inconsistent state means that this queue does indeed have data, but
116     /// it does not currently have access to it at this time.
117     pub fn pop(&self) -> PopResult<T> {
118         unsafe {
119             let tail = *self.tail.get();
120             let next = (*tail).next.load(Ordering::Acquire);
121
122             if !next.is_null() {
123                 *self.tail.get() = next;
124                 assert!((*tail).value.is_none());
125                 assert!((*next).value.is_some());
126                 let ret = (*next).value.take().unwrap();
127                 let _: Box<Node<T>> = Box::from_raw(tail);
128                 return Data(ret);
129             }
130
131             if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent}
132         }
133     }
134 }
135
136 impl<T> Drop for Queue<T> {
137     fn drop(&mut self) {
138         unsafe {
139             let mut cur = *self.tail.get();
140             while !cur.is_null() {
141                 let next = (*cur).next.load(Ordering::Relaxed);
142                 let _: Box<Node<T>> = Box::from_raw(cur);
143                 cur = next;
144             }
145         }
146     }
147 }
148
149 #[cfg(test)]
150 mod tests {
151     use sync::mpsc::channel;
152     use super::{Queue, Data, Empty, Inconsistent};
153     use sync::Arc;
154     use thread;
155
156     #[test]
157     fn test_full() {
158         let q: Queue<Box<_>> = Queue::new();
159         q.push(box 1);
160         q.push(box 2);
161     }
162
163     #[test]
164     fn test() {
165         let nthreads = 8;
166         let nmsgs = 1000;
167         let q = Queue::new();
168         match q.pop() {
169             Empty => {}
170             Inconsistent | Data(..) => panic!()
171         }
172         let (tx, rx) = channel();
173         let q = Arc::new(q);
174
175         for _ in 0..nthreads {
176             let tx = tx.clone();
177             let q = q.clone();
178             thread::spawn(move|| {
179                 for i in 0..nmsgs {
180                     q.push(i);
181                 }
182                 tx.send(()).unwrap();
183             });
184         }
185
186         let mut i = 0;
187         while i < nthreads * nmsgs {
188             match q.pop() {
189                 Empty | Inconsistent => {},
190                 Data(_) => { i += 1 }
191             }
192         }
193         drop(tx);
194         for _ in 0..nthreads {
195             rx.recv().unwrap();
196         }
197     }
198 }