]> git.lizzy.rs Git - rust.git/blob - src/liballoc/arc.rs
auto merge of #14801 : pcwalton/rust/name-shadowing-in-one-pattern, r=alexcrichton
[rust.git] / src / liballoc / arc.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
12  * Concurrency-enabled mechanisms for sharing mutable and/or immutable state
13  * between tasks.
14  */
15
16 use core::atomics;
17 use core::clone::Clone;
18 use core::kinds::{Share, Send};
19 use core::mem::{min_align_of, size_of, drop};
20 use core::mem;
21 use core::ops::{Drop, Deref};
22 use core::option::{Some, None, Option};
23 use core::ptr;
24 use core::ptr::RawPtr;
25 use heap::deallocate;
26
27 /// An atomically reference counted wrapper for shared state.
28 ///
29 /// # Example
30 ///
31 /// In this example, a large vector of floats is shared between several tasks.
32 /// With simple pipes, without `Arc`, a copy would have to be made for each
33 /// task.
34 ///
35 /// ```rust
36 /// use std::sync::Arc;
37 ///
38 /// fn main() {
39 ///     let numbers = Vec::from_fn(100, |i| i as f32);
40 ///     let shared_numbers = Arc::new(numbers);
41 ///
42 ///     for _ in range(0, 10) {
43 ///         let child_numbers = shared_numbers.clone();
44 ///
45 ///         spawn(proc() {
46 ///             let local_numbers = child_numbers.as_slice();
47 ///
48 ///             // Work with the local numbers
49 ///         });
50 ///     }
51 /// }
52 /// ```
53 #[unsafe_no_drop_flag]
54 pub struct Arc<T> {
55     // FIXME #12808: strange name to try to avoid interfering with
56     // field accesses of the contained type via Deref
57     _ptr: *mut ArcInner<T>,
58 }
59
60 /// A weak pointer to an `Arc`.
61 ///
62 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be
63 /// used to break cycles between `Arc` pointers.
64 #[unsafe_no_drop_flag]
65 pub struct Weak<T> {
66     // FIXME #12808: strange name to try to avoid interfering with
67     // field accesses of the contained type via Deref
68     _ptr: *mut ArcInner<T>,
69 }
70
71 struct ArcInner<T> {
72     strong: atomics::AtomicUint,
73     weak: atomics::AtomicUint,
74     data: T,
75 }
76
77 impl<T: Share + Send> Arc<T> {
78     /// Create an atomically reference counted wrapper.
79     #[inline]
80     pub fn new(data: T) -> Arc<T> {
81         // Start the weak pointer count as 1 which is the weak pointer that's
82         // held by all the strong pointers (kinda), see std/rc.rs for more info
83         let x = box ArcInner {
84             strong: atomics::AtomicUint::new(1),
85             weak: atomics::AtomicUint::new(1),
86             data: data,
87         };
88         Arc { _ptr: unsafe { mem::transmute(x) } }
89     }
90
91     #[inline]
92     fn inner<'a>(&'a self) -> &'a ArcInner<T> {
93         // This unsafety is ok because while this arc is alive we're guaranteed
94         // that the inner pointer is valid. Furthermore, we know that the
95         // `ArcInner` structure itself is `Share` because the inner data is
96         // `Share` as well, so we're ok loaning out an immutable pointer to
97         // these contents.
98         unsafe { &*self._ptr }
99     }
100
101     /// Downgrades a strong pointer to a weak pointer
102     ///
103     /// Weak pointers will not keep the data alive. Once all strong references
104     /// to the underlying data have been dropped, the data itself will be
105     /// destroyed.
106     pub fn downgrade(&self) -> Weak<T> {
107         // See the clone() impl for why this is relaxed
108         self.inner().weak.fetch_add(1, atomics::Relaxed);
109         Weak { _ptr: self._ptr }
110     }
111 }
112
113 impl<T: Share + Send> Clone for Arc<T> {
114     /// Duplicate an atomically reference counted wrapper.
115     ///
116     /// The resulting two `Arc` objects will point to the same underlying data
117     /// object. However, one of the `Arc` objects can be sent to another task,
118     /// allowing them to share the underlying data.
119     #[inline]
120     fn clone(&self) -> Arc<T> {
121         // Using a relaxed ordering is alright here, as knowledge of the
122         // original reference prevents other threads from erroneously deleting
123         // the object.
124         //
125         // As explained in the [Boost documentation][1], Increasing the
126         // reference counter can always be done with memory_order_relaxed: New
127         // references to an object can only be formed from an existing
128         // reference, and passing an existing reference from one thread to
129         // another must already provide any required synchronization.
130         //
131         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
132         self.inner().strong.fetch_add(1, atomics::Relaxed);
133         Arc { _ptr: self._ptr }
134     }
135 }
136
137 impl<T: Send + Share> Deref<T> for Arc<T> {
138     #[inline]
139     fn deref<'a>(&'a self) -> &'a T {
140         &self.inner().data
141     }
142 }
143
144 impl<T: Send + Share + Clone> Arc<T> {
145     /// Acquires a mutable pointer to the inner contents by guaranteeing that
146     /// the reference count is one (no sharing is possible).
147     ///
148     /// This is also referred to as a copy-on-write operation because the inner
149     /// data is cloned if the reference count is greater than one.
150     #[inline]
151     #[experimental]
152     pub fn make_unique<'a>(&'a mut self) -> &'a mut T {
153         // Note that we hold a strong reference, which also counts as
154         // a weak reference, so we only clone if there is an
155         // additional reference of either kind.
156         if self.inner().strong.load(atomics::SeqCst) != 1 ||
157            self.inner().weak.load(atomics::SeqCst) != 1 {
158             *self = Arc::new(self.deref().clone())
159         }
160         // This unsafety is ok because we're guaranteed that the pointer
161         // returned is the *only* pointer that will ever be returned to T. Our
162         // reference count is guaranteed to be 1 at this point, and we required
163         // the Arc itself to be `mut`, so we're returning the only possible
164         // reference to the inner data.
165         let inner = unsafe { &mut *self._ptr };
166         &mut inner.data
167     }
168 }
169
170 #[unsafe_destructor]
171 impl<T: Share + Send> Drop for Arc<T> {
172     fn drop(&mut self) {
173         // This structure has #[unsafe_no_drop_flag], so this drop glue may run
174         // more than once (but it is guaranteed to be zeroed after the first if
175         // it's run more than once)
176         if self._ptr.is_null() { return }
177
178         // Because `fetch_sub` is already atomic, we do not need to synchronize
179         // with other threads unless we are going to delete the object. This
180         // same logic applies to the below `fetch_sub` to the `weak` count.
181         if self.inner().strong.fetch_sub(1, atomics::Release) != 1 { return }
182
183         // This fence is needed to prevent reordering of use of the data and
184         // deletion of the data. Because it is marked `Release`, the
185         // decreasing of the reference count synchronizes with this `Acquire`
186         // fence. This means that use of the data happens before decreasing
187         // the refernce count, which happens before this fence, which
188         // happens before the deletion of the data.
189         //
190         // As explained in the [Boost documentation][1],
191         //
192         // It is important to enforce any possible access to the object in
193         // one thread (through an existing reference) to *happen before*
194         // deleting the object in a different thread. This is achieved by a
195         // "release" operation after dropping a reference (any access to the
196         // object through this reference must obviously happened before),
197         // and an "acquire" operation before deleting the object.
198         //
199         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
200         atomics::fence(atomics::Acquire);
201
202         // Destroy the data at this time, even though we may not free the box
203         // allocation itself (there may still be weak pointers lying around).
204         unsafe { drop(ptr::read(&self.inner().data)); }
205
206         if self.inner().weak.fetch_sub(1, atomics::Release) == 1 {
207             atomics::fence(atomics::Acquire);
208             unsafe { deallocate(self._ptr as *mut u8, size_of::<ArcInner<T>>(),
209                                 min_align_of::<ArcInner<T>>()) }
210         }
211     }
212 }
213
214 impl<T: Share + Send> Weak<T> {
215     /// Attempts to upgrade this weak reference to a strong reference.
216     ///
217     /// This method will fail to upgrade this reference if the strong reference
218     /// count has already reached 0, but if there are still other active strong
219     /// references this function will return a new strong reference to the data
220     pub fn upgrade(&self) -> Option<Arc<T>> {
221         // We use a CAS loop to increment the strong count instead of a
222         // fetch_add because once the count hits 0 is must never be above 0.
223         let inner = self.inner();
224         loop {
225             let n = inner.strong.load(atomics::SeqCst);
226             if n == 0 { return None }
227             let old = inner.strong.compare_and_swap(n, n + 1, atomics::SeqCst);
228             if old == n { return Some(Arc { _ptr: self._ptr }) }
229         }
230     }
231
232     #[inline]
233     fn inner<'a>(&'a self) -> &'a ArcInner<T> {
234         // See comments above for why this is "safe"
235         unsafe { &*self._ptr }
236     }
237 }
238
239 impl<T: Share + Send> Clone for Weak<T> {
240     #[inline]
241     fn clone(&self) -> Weak<T> {
242         // See comments in Arc::clone() for why this is relaxed
243         self.inner().weak.fetch_add(1, atomics::Relaxed);
244         Weak { _ptr: self._ptr }
245     }
246 }
247
248 #[unsafe_destructor]
249 impl<T: Share + Send> Drop for Weak<T> {
250     fn drop(&mut self) {
251         // see comments above for why this check is here
252         if self._ptr.is_null() { return }
253
254         // If we find out that we were the last weak pointer, then its time to
255         // deallocate the data entirely. See the discussion in Arc::drop() about
256         // the memory orderings
257         if self.inner().weak.fetch_sub(1, atomics::Release) == 1 {
258             atomics::fence(atomics::Acquire);
259             unsafe { deallocate(self._ptr as *mut u8, size_of::<ArcInner<T>>(),
260                                 min_align_of::<ArcInner<T>>()) }
261         }
262     }
263 }
264
265 #[cfg(test)]
266 #[allow(experimental)]
267 mod tests {
268     use std::clone::Clone;
269     use std::comm::channel;
270     use std::mem::drop;
271     use std::ops::Drop;
272     use std::option::{Option, Some, None};
273     use std::sync::atomics;
274     use std::task;
275     use std::vec::Vec;
276     use super::{Arc, Weak};
277     use std::sync::Mutex;
278
279     struct Canary(*mut atomics::AtomicUint);
280
281     impl Drop for Canary
282     {
283         fn drop(&mut self) {
284             unsafe {
285                 match *self {
286                     Canary(c) => {
287                         (*c).fetch_add(1, atomics::SeqCst);
288                     }
289                 }
290             }
291         }
292     }
293
294     #[test]
295     fn manually_share_arc() {
296         let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
297         let arc_v = Arc::new(v);
298
299         let (tx, rx) = channel();
300
301         task::spawn(proc() {
302             let arc_v: Arc<Vec<int>> = rx.recv();
303             assert_eq!(*arc_v.get(3), 4);
304         });
305
306         tx.send(arc_v.clone());
307
308         assert_eq!(*arc_v.get(2), 3);
309         assert_eq!(*arc_v.get(4), 5);
310
311         info!("{:?}", arc_v);
312     }
313
314     #[test]
315     fn test_cowarc_clone_make_unique() {
316         let mut cow0 = Arc::new(75u);
317         let mut cow1 = cow0.clone();
318         let mut cow2 = cow1.clone();
319
320         assert!(75 == *cow0.make_unique());
321         assert!(75 == *cow1.make_unique());
322         assert!(75 == *cow2.make_unique());
323
324         *cow0.make_unique() += 1;
325         *cow1.make_unique() += 2;
326         *cow2.make_unique() += 3;
327
328         assert!(76 == *cow0);
329         assert!(77 == *cow1);
330         assert!(78 == *cow2);
331
332         // none should point to the same backing memory
333         assert!(*cow0 != *cow1);
334         assert!(*cow0 != *cow2);
335         assert!(*cow1 != *cow2);
336     }
337
338     #[test]
339     fn test_cowarc_clone_unique2() {
340         let mut cow0 = Arc::new(75u);
341         let cow1 = cow0.clone();
342         let cow2 = cow1.clone();
343
344         assert!(75 == *cow0);
345         assert!(75 == *cow1);
346         assert!(75 == *cow2);
347
348         *cow0.make_unique() += 1;
349
350         assert!(76 == *cow0);
351         assert!(75 == *cow1);
352         assert!(75 == *cow2);
353
354         // cow1 and cow2 should share the same contents
355         // cow0 should have a unique reference
356         assert!(*cow0 != *cow1);
357         assert!(*cow0 != *cow2);
358         assert!(*cow1 == *cow2);
359     }
360
361     #[test]
362     fn test_cowarc_clone_weak() {
363         let mut cow0 = Arc::new(75u);
364         let cow1_weak = cow0.downgrade();
365
366         assert!(75 == *cow0);
367         assert!(75 == *cow1_weak.upgrade().unwrap());
368
369         *cow0.make_unique() += 1;
370
371         assert!(76 == *cow0);
372         assert!(cow1_weak.upgrade().is_none());
373     }
374
375     #[test]
376     fn test_live() {
377         let x = Arc::new(5);
378         let y = x.downgrade();
379         assert!(y.upgrade().is_some());
380     }
381
382     #[test]
383     fn test_dead() {
384         let x = Arc::new(5);
385         let y = x.downgrade();
386         drop(x);
387         assert!(y.upgrade().is_none());
388     }
389
390     #[test]
391     fn weak_self_cyclic() {
392         struct Cycle {
393             x: Mutex<Option<Weak<Cycle>>>
394         }
395
396         let a = Arc::new(Cycle { x: Mutex::new(None) });
397         let b = a.clone().downgrade();
398         *a.x.lock() = Some(b);
399
400         // hopefully we don't double-free (or leak)...
401     }
402
403     #[test]
404     fn drop_arc() {
405         let mut canary = atomics::AtomicUint::new(0);
406         let x = Arc::new(Canary(&mut canary as *mut atomics::AtomicUint));
407         drop(x);
408         assert!(canary.load(atomics::Acquire) == 1);
409     }
410
411     #[test]
412     fn drop_arc_weak() {
413         let mut canary = atomics::AtomicUint::new(0);
414         let arc = Arc::new(Canary(&mut canary as *mut atomics::AtomicUint));
415         let arc_weak = arc.downgrade();
416         assert!(canary.load(atomics::Acquire) == 0);
417         drop(arc);
418         assert!(canary.load(atomics::Acquire) == 1);
419         drop(arc_weak);
420     }
421 }