]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/mpsc/mpsc_queue.rs
Merge pull request #20512 from bjz/rustdoc
[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 tasks, 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 #![experimental]
39
40 // http://www.1024cores.net/home/lock-free-algorithms
41 //                         /queues/non-intrusive-mpsc-node-based-queue
42
43 pub use self::PopResult::*;
44
45 use core::prelude::*;
46
47 use alloc::boxed::Box;
48 use core::mem;
49 use core::cell::UnsafeCell;
50
51 use sync::atomic::{AtomicPtr, Ordering};
52
53 /// A result of the `pop` function.
54 pub enum PopResult<T> {
55     /// Some data has been popped
56     Data(T),
57     /// The queue is empty
58     Empty,
59     /// The queue is in an inconsistent state. Popping data should succeed, but
60     /// some pushers have yet to make enough progress in order allow a pop to
61     /// succeed. It is recommended that a pop() occur "in the near future" in
62     /// order to see if the sender has made progress or not
63     Inconsistent,
64 }
65
66 struct Node<T> {
67     next: AtomicPtr<Node<T>>,
68     value: Option<T>,
69 }
70
71 /// The multi-producer single-consumer structure. This is not cloneable, but it
72 /// may be safely shared so long as it is guaranteed that there is only one
73 /// popper at a time (many pushers are allowed).
74 pub struct Queue<T> {
75     head: AtomicPtr<Node<T>>,
76     tail: UnsafeCell<*mut Node<T>>,
77 }
78
79 unsafe impl<T:Send> Send for Queue<T> { }
80 unsafe impl<T:Send> Sync for Queue<T> { }
81
82 impl<T> Node<T> {
83     unsafe fn new(v: Option<T>) -> *mut Node<T> {
84         mem::transmute(box Node {
85             next: AtomicPtr::new(0 as *mut Node<T>),
86             value: v,
87         })
88     }
89 }
90
91 impl<T: Send> Queue<T> {
92     /// Creates a new queue that is safe to share among multiple producers and
93     /// one consumer.
94     pub fn new() -> Queue<T> {
95         let stub = unsafe { Node::new(None) };
96         Queue {
97             head: AtomicPtr::new(stub),
98             tail: UnsafeCell::new(stub),
99         }
100     }
101
102     /// Pushes a new value onto this queue.
103     pub fn push(&self, t: T) {
104         unsafe {
105             let n = Node::new(Some(t));
106             let prev = self.head.swap(n, Ordering::AcqRel);
107             (*prev).next.store(n, Ordering::Release);
108         }
109     }
110
111     /// Pops some data from this queue.
112     ///
113     /// Note that the current implementation means that this function cannot
114     /// return `Option<T>`. It is possible for this queue to be in an
115     /// inconsistent state where many pushes have succeeded and completely
116     /// finished, but pops cannot return `Some(t)`. This inconsistent state
117     /// happens when a pusher is pre-empted at an inopportune moment.
118     ///
119     /// This inconsistent state means that this queue does indeed have data, but
120     /// it does not currently have access to it at this time.
121     pub fn pop(&self) -> PopResult<T> {
122         unsafe {
123             let tail = *self.tail.get();
124             let next = (*tail).next.load(Ordering::Acquire);
125
126             if !next.is_null() {
127                 *self.tail.get() = next;
128                 assert!((*tail).value.is_none());
129                 assert!((*next).value.is_some());
130                 let ret = (*next).value.take().unwrap();
131                 let _: Box<Node<T>> = mem::transmute(tail);
132                 return Data(ret);
133             }
134
135             if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent}
136         }
137     }
138 }
139
140 #[unsafe_destructor]
141 impl<T: Send> Drop for Queue<T> {
142     fn drop(&mut self) {
143         unsafe {
144             let mut cur = *self.tail.get();
145             while !cur.is_null() {
146                 let next = (*cur).next.load(Ordering::Relaxed);
147                 let _: Box<Node<T>> = mem::transmute(cur);
148                 cur = next;
149             }
150         }
151     }
152 }
153
154 #[cfg(test)]
155 mod tests {
156     use prelude::v1::*;
157
158     use sync::mpsc::channel;
159     use super::{Queue, Data, Empty, Inconsistent};
160     use sync::Arc;
161     use thread::Thread;
162
163     #[test]
164     fn test_full() {
165         let q = Queue::new();
166         q.push(box 1i);
167         q.push(box 2i);
168     }
169
170     #[test]
171     fn test() {
172         let nthreads = 8u;
173         let nmsgs = 1000u;
174         let q = Queue::new();
175         match q.pop() {
176             Empty => {}
177             Inconsistent | Data(..) => panic!()
178         }
179         let (tx, rx) = channel();
180         let q = Arc::new(q);
181
182         for _ in range(0, nthreads) {
183             let tx = tx.clone();
184             let q = q.clone();
185             Thread::spawn(move|| {
186                 for i in range(0, nmsgs) {
187                     q.push(i);
188                 }
189                 tx.send(()).unwrap();
190             }).detach();
191         }
192
193         let mut i = 0u;
194         while i < nthreads * nmsgs {
195             match q.pop() {
196                 Empty | Inconsistent => {},
197                 Data(_) => { i += 1 }
198             }
199         }
200         drop(tx);
201         for _ in range(0, nthreads) {
202             rx.recv().unwrap();
203         }
204     }
205 }