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