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.
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.
11 #![stable(feature = "rust1", since = "1.0.0")]
13 //! Threadsafe reference-counted boxes (the `Arc<T>` type).
15 //! The `Arc<T>` type provides shared ownership of an immutable value.
16 //! Destruction is deterministic, and will occur as soon as the last owner is
17 //! gone. It is marked as `Send` because it uses atomic reference counting.
19 //! If you do not need thread-safety, and just need shared ownership, consider
20 //! the [`Rc<T>` type](../rc/struct.Rc.html). It is the same as `Arc<T>`, but
21 //! does not use atomics, making it both thread-unsafe as well as significantly
22 //! faster when updating the reference count.
24 //! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer
25 //! to the box. A `Weak<T>` pointer can be upgraded to an `Arc<T>` pointer, but
26 //! will return `None` if the value has already been dropped.
28 //! For example, a tree with parent pointers can be represented by putting the
29 //! nodes behind strong `Arc<T>` pointers, and then storing the parent pointers
30 //! as `Weak<T>` pointers.
34 //! Sharing some immutable data between tasks:
37 //! use std::sync::Arc;
40 //! let five = Arc::new(5);
43 //! let five = five.clone();
45 //! thread::spawn(move || {
46 //! println!("{:?}", five);
51 //! Sharing mutable data safely between tasks with a `Mutex`:
54 //! use std::sync::{Arc, Mutex};
57 //! let five = Arc::new(Mutex::new(5));
60 //! let five = five.clone();
62 //! thread::spawn(move || {
63 //! let mut number = five.lock().unwrap();
67 //! println!("{}", *number); // prints 6
77 use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
79 use core::cmp::Ordering;
80 use core::default::Default;
81 use core::mem::{min_align_of, size_of};
83 use core::nonzero::NonZero;
86 use core::hash::{Hash, Hasher};
89 /// An atomically reference counted wrapper for shared state.
93 /// In this example, a large vector of floats is shared between several tasks.
94 /// With simple pipes, without `Arc`, a copy would have to be made for each
97 /// When you clone an `Arc<T>`, it will create another pointer to the data and
98 /// increase the reference counter.
101 /// # #![feature(alloc, core)]
102 /// use std::sync::Arc;
106 /// let numbers: Vec<_> = (0..100u32).collect();
107 /// let shared_numbers = Arc::new(numbers);
110 /// let child_numbers = shared_numbers.clone();
112 /// thread::spawn(move || {
113 /// let local_numbers = &child_numbers[..];
115 /// // Work with the local numbers
120 #[unsafe_no_drop_flag]
121 #[stable(feature = "rust1", since = "1.0.0")]
123 // FIXME #12808: strange name to try to avoid interfering with
124 // field accesses of the contained type via Deref
125 _ptr: NonZero<*mut ArcInner<T>>,
128 unsafe impl<T: Sync + Send> Send for Arc<T> { }
129 unsafe impl<T: Sync + Send> Sync for Arc<T> { }
132 /// A weak pointer to an `Arc`.
134 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be
135 /// used to break cycles between `Arc` pointers.
136 #[unsafe_no_drop_flag]
137 #[unstable(feature = "alloc",
138 reason = "Weak pointers may not belong in this module.")]
140 // FIXME #12808: strange name to try to avoid interfering with
141 // field accesses of the contained type via Deref
142 _ptr: NonZero<*mut ArcInner<T>>,
145 unsafe impl<T: Sync + Send> Send for Weak<T> { }
146 unsafe impl<T: Sync + Send> Sync for Weak<T> { }
148 #[stable(feature = "rust1", since = "1.0.0")]
149 impl<T: fmt::Debug> fmt::Debug for Weak<T> {
150 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
156 strong: atomic::AtomicUsize,
157 weak: atomic::AtomicUsize,
161 unsafe impl<T: Sync + Send> Send for ArcInner<T> {}
162 unsafe impl<T: Sync + Send> Sync for ArcInner<T> {}
165 /// Constructs a new `Arc<T>`.
170 /// use std::sync::Arc;
172 /// let five = Arc::new(5);
175 #[stable(feature = "rust1", since = "1.0.0")]
176 pub fn new(data: T) -> Arc<T> {
177 // Start the weak pointer count as 1 which is the weak pointer that's
178 // held by all the strong pointers (kinda), see std/rc.rs for more info
179 let x: Box<_> = box ArcInner {
180 strong: atomic::AtomicUsize::new(1),
181 weak: atomic::AtomicUsize::new(1),
184 Arc { _ptr: unsafe { NonZero::new(mem::transmute(x)) } }
187 /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
192 /// # #![feature(alloc)]
193 /// use std::sync::Arc;
195 /// let five = Arc::new(5);
197 /// let weak_five = five.downgrade();
199 #[unstable(feature = "alloc",
200 reason = "Weak pointers may not belong in this module.")]
201 pub fn downgrade(&self) -> Weak<T> {
202 // See the clone() impl for why this is relaxed
203 self.inner().weak.fetch_add(1, Relaxed);
204 Weak { _ptr: self._ptr }
210 fn inner(&self) -> &ArcInner<T> {
211 // This unsafety is ok because while this arc is alive we're guaranteed
212 // that the inner pointer is valid. Furthermore, we know that the
213 // `ArcInner` structure itself is `Sync` because the inner data is
214 // `Sync` as well, so we're ok loaning out an immutable pointer to these
216 unsafe { &**self._ptr }
219 // Non-inlined part of `drop`.
221 unsafe fn drop_slow(&mut self) {
222 let ptr = *self._ptr;
224 // Destroy the data at this time, even though we may not free the box
225 // allocation itself (there may still be weak pointers lying around).
226 drop(ptr::read(&self.inner().data));
228 if self.inner().weak.fetch_sub(1, Release) == 1 {
229 atomic::fence(Acquire);
230 deallocate(ptr as *mut u8, size_of::<ArcInner<T>>(), min_align_of::<ArcInner<T>>())
235 /// Get the number of weak references to this value.
237 #[unstable(feature = "alloc")]
238 pub fn weak_count<T>(this: &Arc<T>) -> usize { this.inner().weak.load(SeqCst) - 1 }
240 /// Get the number of strong references to this value.
242 #[unstable(feature = "alloc")]
243 pub fn strong_count<T>(this: &Arc<T>) -> usize { this.inner().strong.load(SeqCst) }
246 /// Returns a mutable reference to the contained value if the `Arc<T>` is unique.
248 /// Returns `None` if the `Arc<T>` is not unique.
253 /// # #![feature(alloc)]
254 /// extern crate alloc;
256 /// use alloc::arc::{Arc, get_mut};
258 /// let mut x = Arc::new(3);
259 /// *get_mut(&mut x).unwrap() = 4;
260 /// assert_eq!(*x, 4);
262 /// let _y = x.clone();
263 /// assert!(get_mut(&mut x).is_none());
267 #[unstable(feature = "alloc")]
268 pub fn get_mut<T>(this: &mut Arc<T>) -> Option<&mut T> {
269 if strong_count(this) == 1 && weak_count(this) == 0 {
270 // This unsafety is ok because we're guaranteed that the pointer
271 // returned is the *only* pointer that will ever be returned to T. Our
272 // reference count is guaranteed to be 1 at this point, and we required
273 // the Arc itself to be `mut`, so we're returning the only possible
274 // reference to the inner data.
275 let inner = unsafe { &mut **this._ptr };
276 Some(&mut inner.data)
282 #[stable(feature = "rust1", since = "1.0.0")]
283 impl<T> Clone for Arc<T> {
284 /// Makes a clone of the `Arc<T>`.
286 /// This increases the strong reference count.
291 /// # #![feature(alloc)]
292 /// use std::sync::Arc;
294 /// let five = Arc::new(5);
299 fn clone(&self) -> Arc<T> {
300 // Using a relaxed ordering is alright here, as knowledge of the
301 // original reference prevents other threads from erroneously deleting
304 // As explained in the [Boost documentation][1], Increasing the
305 // reference counter can always be done with memory_order_relaxed: New
306 // references to an object can only be formed from an existing
307 // reference, and passing an existing reference from one thread to
308 // another must already provide any required synchronization.
310 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
311 self.inner().strong.fetch_add(1, Relaxed);
312 Arc { _ptr: self._ptr }
316 #[stable(feature = "rust1", since = "1.0.0")]
317 impl<T> Deref for Arc<T> {
321 fn deref(&self) -> &T {
326 impl<T: Clone> Arc<T> {
327 /// Make a mutable reference from the given `Arc<T>`.
329 /// This is also referred to as a copy-on-write operation because the inner
330 /// data is cloned if the reference count is greater than one.
335 /// # #![feature(alloc)]
336 /// use std::sync::Arc;
338 /// let mut five = Arc::new(5);
340 /// let mut_five = five.make_unique();
343 #[unstable(feature = "alloc")]
344 pub fn make_unique(&mut self) -> &mut T {
345 // Note that we hold a strong reference, which also counts as a weak
346 // reference, so we only clone if there is an additional reference of
348 if self.inner().strong.load(SeqCst) != 1 ||
349 self.inner().weak.load(SeqCst) != 1 {
350 *self = Arc::new((**self).clone())
352 // As with `get_mut()`, the unsafety is ok because our reference was
353 // either unique to begin with, or became one upon cloning the contents.
354 let inner = unsafe { &mut **self._ptr };
360 #[stable(feature = "rust1", since = "1.0.0")]
361 impl<T> Drop for Arc<T> {
362 /// Drops the `Arc<T>`.
364 /// This will decrement the strong reference count. If the strong reference
365 /// count becomes zero and the only other references are `Weak<T>` ones,
366 /// `drop`s the inner value.
371 /// # #![feature(alloc)]
372 /// use std::sync::Arc;
375 /// let five = Arc::new(5);
379 /// drop(five); // explicit drop
382 /// let five = Arc::new(5);
386 /// } // implicit drop
390 // This structure has #[unsafe_no_drop_flag], so this drop glue may run
391 // more than once (but it is guaranteed to be zeroed after the first if
392 // it's run more than once)
393 let ptr = *self._ptr;
394 // if ptr.is_null() { return }
395 if ptr.is_null() || ptr as usize == mem::POST_DROP_USIZE { return }
397 // Because `fetch_sub` is already atomic, we do not need to synchronize
398 // with other threads unless we are going to delete the object. This
399 // same logic applies to the below `fetch_sub` to the `weak` count.
400 if self.inner().strong.fetch_sub(1, Release) != 1 { return }
402 // This fence is needed to prevent reordering of use of the data and
403 // deletion of the data. Because it is marked `Release`, the decreasing
404 // of the reference count synchronizes with this `Acquire` fence. This
405 // means that use of the data happens before decreasing the reference
406 // count, which happens before this fence, which happens before the
407 // deletion of the data.
409 // As explained in the [Boost documentation][1],
411 // > It is important to enforce any possible access to the object in one
412 // > thread (through an existing reference) to *happen before* deleting
413 // > the object in a different thread. This is achieved by a "release"
414 // > operation after dropping a reference (any access to the object
415 // > through this reference must obviously happened before), and an
416 // > "acquire" operation before deleting the object.
418 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
419 atomic::fence(Acquire);
427 #[unstable(feature = "alloc",
428 reason = "Weak pointers may not belong in this module.")]
430 /// Upgrades a weak reference to a strong reference.
432 /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
434 /// Returns `None` if there were no strong references and the data was
440 /// # #![feature(alloc)]
441 /// use std::sync::Arc;
443 /// let five = Arc::new(5);
445 /// let weak_five = five.downgrade();
447 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
449 pub fn upgrade(&self) -> Option<Arc<T>> {
450 // We use a CAS loop to increment the strong count instead of a
451 // fetch_add because once the count hits 0 it must never be above 0.
452 let inner = self.inner();
454 let n = inner.strong.load(SeqCst);
455 if n == 0 { return None }
456 let old = inner.strong.compare_and_swap(n, n + 1, SeqCst);
457 if old == n { return Some(Arc { _ptr: self._ptr }) }
462 fn inner(&self) -> &ArcInner<T> {
463 // See comments above for why this is "safe"
464 unsafe { &**self._ptr }
468 #[unstable(feature = "alloc",
469 reason = "Weak pointers may not belong in this module.")]
470 impl<T> Clone for Weak<T> {
471 /// Makes a clone of the `Weak<T>`.
473 /// This increases the weak reference count.
478 /// # #![feature(alloc)]
479 /// use std::sync::Arc;
481 /// let weak_five = Arc::new(5).downgrade();
483 /// weak_five.clone();
486 fn clone(&self) -> Weak<T> {
487 // See comments in Arc::clone() for why this is relaxed
488 self.inner().weak.fetch_add(1, Relaxed);
489 Weak { _ptr: self._ptr }
494 #[stable(feature = "rust1", since = "1.0.0")]
495 impl<T> Drop for Weak<T> {
496 /// Drops the `Weak<T>`.
498 /// This will decrement the weak reference count.
503 /// # #![feature(alloc)]
504 /// use std::sync::Arc;
507 /// let five = Arc::new(5);
508 /// let weak_five = five.downgrade();
512 /// drop(weak_five); // explicit drop
515 /// let five = Arc::new(5);
516 /// let weak_five = five.downgrade();
520 /// } // implicit drop
523 let ptr = *self._ptr;
525 // see comments above for why this check is here
526 if ptr.is_null() || ptr as usize == mem::POST_DROP_USIZE { return }
528 // If we find out that we were the last weak pointer, then its time to
529 // deallocate the data entirely. See the discussion in Arc::drop() about
530 // the memory orderings
531 if self.inner().weak.fetch_sub(1, Release) == 1 {
532 atomic::fence(Acquire);
533 unsafe { deallocate(ptr as *mut u8, size_of::<ArcInner<T>>(),
534 min_align_of::<ArcInner<T>>()) }
539 #[stable(feature = "rust1", since = "1.0.0")]
540 impl<T: PartialEq> PartialEq for Arc<T> {
541 /// Equality for two `Arc<T>`s.
543 /// Two `Arc<T>`s are equal if their inner value are equal.
548 /// use std::sync::Arc;
550 /// let five = Arc::new(5);
552 /// five == Arc::new(5);
554 fn eq(&self, other: &Arc<T>) -> bool { *(*self) == *(*other) }
556 /// Inequality for two `Arc<T>`s.
558 /// Two `Arc<T>`s are unequal if their inner value are unequal.
563 /// use std::sync::Arc;
565 /// let five = Arc::new(5);
567 /// five != Arc::new(5);
569 fn ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) }
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl<T: PartialOrd> PartialOrd for Arc<T> {
573 /// Partial comparison for two `Arc<T>`s.
575 /// The two are compared by calling `partial_cmp()` on their inner values.
580 /// use std::sync::Arc;
582 /// let five = Arc::new(5);
584 /// five.partial_cmp(&Arc::new(5));
586 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
587 (**self).partial_cmp(&**other)
590 /// Less-than comparison for two `Arc<T>`s.
592 /// The two are compared by calling `<` on their inner values.
597 /// use std::sync::Arc;
599 /// let five = Arc::new(5);
601 /// five < Arc::new(5);
603 fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) }
605 /// 'Less-than or equal to' comparison for two `Arc<T>`s.
607 /// The two are compared by calling `<=` on their inner values.
612 /// use std::sync::Arc;
614 /// let five = Arc::new(5);
616 /// five <= Arc::new(5);
618 fn le(&self, other: &Arc<T>) -> bool { *(*self) <= *(*other) }
620 /// Greater-than comparison for two `Arc<T>`s.
622 /// The two are compared by calling `>` on their inner values.
627 /// use std::sync::Arc;
629 /// let five = Arc::new(5);
631 /// five > Arc::new(5);
633 fn gt(&self, other: &Arc<T>) -> bool { *(*self) > *(*other) }
635 /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
637 /// The two are compared by calling `>=` on their inner values.
642 /// use std::sync::Arc;
644 /// let five = Arc::new(5);
646 /// five >= Arc::new(5);
648 fn ge(&self, other: &Arc<T>) -> bool { *(*self) >= *(*other) }
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<T: Ord> Ord for Arc<T> {
652 fn cmp(&self, other: &Arc<T>) -> Ordering { (**self).cmp(&**other) }
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl<T: Eq> Eq for Arc<T> {}
657 #[stable(feature = "rust1", since = "1.0.0")]
658 impl<T: fmt::Display> fmt::Display for Arc<T> {
659 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
660 fmt::Display::fmt(&**self, f)
664 #[stable(feature = "rust1", since = "1.0.0")]
665 impl<T: fmt::Debug> fmt::Debug for Arc<T> {
666 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
667 fmt::Debug::fmt(&**self, f)
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl<T> fmt::Pointer for Arc<T> {
673 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
674 fmt::Pointer::fmt(&*self._ptr, f)
678 #[stable(feature = "rust1", since = "1.0.0")]
679 impl<T: Default + Sync + Send> Default for Arc<T> {
680 #[stable(feature = "rust1", since = "1.0.0")]
681 fn default() -> Arc<T> { Arc::new(Default::default()) }
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl<T: Hash> Hash for Arc<T> {
686 fn hash<H: Hasher>(&self, state: &mut H) {
693 use std::clone::Clone;
694 use std::sync::mpsc::channel;
697 use std::option::Option;
698 use std::option::Option::{Some, None};
699 use std::sync::atomic;
700 use std::sync::atomic::Ordering::{Acquire, SeqCst};
703 use super::{Arc, Weak, get_mut, weak_count, strong_count};
704 use std::sync::Mutex;
706 struct Canary(*mut atomic::AtomicUsize);
714 (*c).fetch_add(1, SeqCst);
722 fn manually_share_arc() {
723 let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
724 let arc_v = Arc::new(v);
726 let (tx, rx) = channel();
728 let _t = thread::spawn(move || {
729 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
730 assert_eq!((*arc_v)[3], 4);
733 tx.send(arc_v.clone()).unwrap();
735 assert_eq!((*arc_v)[2], 3);
736 assert_eq!((*arc_v)[4], 5);
740 fn test_arc_get_mut() {
741 let mut x = Arc::new(3);
742 *get_mut(&mut x).unwrap() = 4;
745 assert!(get_mut(&mut x).is_none());
747 assert!(get_mut(&mut x).is_some());
748 let _w = x.downgrade();
749 assert!(get_mut(&mut x).is_none());
753 fn test_cowarc_clone_make_unique() {
754 let mut cow0 = Arc::new(75);
755 let mut cow1 = cow0.clone();
756 let mut cow2 = cow1.clone();
758 assert!(75 == *cow0.make_unique());
759 assert!(75 == *cow1.make_unique());
760 assert!(75 == *cow2.make_unique());
762 *cow0.make_unique() += 1;
763 *cow1.make_unique() += 2;
764 *cow2.make_unique() += 3;
766 assert!(76 == *cow0);
767 assert!(77 == *cow1);
768 assert!(78 == *cow2);
770 // none should point to the same backing memory
771 assert!(*cow0 != *cow1);
772 assert!(*cow0 != *cow2);
773 assert!(*cow1 != *cow2);
777 fn test_cowarc_clone_unique2() {
778 let mut cow0 = Arc::new(75);
779 let cow1 = cow0.clone();
780 let cow2 = cow1.clone();
782 assert!(75 == *cow0);
783 assert!(75 == *cow1);
784 assert!(75 == *cow2);
786 *cow0.make_unique() += 1;
788 assert!(76 == *cow0);
789 assert!(75 == *cow1);
790 assert!(75 == *cow2);
792 // cow1 and cow2 should share the same contents
793 // cow0 should have a unique reference
794 assert!(*cow0 != *cow1);
795 assert!(*cow0 != *cow2);
796 assert!(*cow1 == *cow2);
800 fn test_cowarc_clone_weak() {
801 let mut cow0 = Arc::new(75);
802 let cow1_weak = cow0.downgrade();
804 assert!(75 == *cow0);
805 assert!(75 == *cow1_weak.upgrade().unwrap());
807 *cow0.make_unique() += 1;
809 assert!(76 == *cow0);
810 assert!(cow1_weak.upgrade().is_none());
816 let y = x.downgrade();
817 assert!(y.upgrade().is_some());
823 let y = x.downgrade();
825 assert!(y.upgrade().is_none());
829 fn weak_self_cyclic() {
831 x: Mutex<Option<Weak<Cycle>>>
834 let a = Arc::new(Cycle { x: Mutex::new(None) });
835 let b = a.clone().downgrade();
836 *a.x.lock().unwrap() = Some(b);
838 // hopefully we don't double-free (or leak)...
843 let mut canary = atomic::AtomicUsize::new(0);
844 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
846 assert!(canary.load(Acquire) == 1);
851 let mut canary = atomic::AtomicUsize::new(0);
852 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
853 let arc_weak = arc.downgrade();
854 assert!(canary.load(Acquire) == 0);
856 assert!(canary.load(Acquire) == 1);
861 fn test_strong_count() {
862 let a = Arc::new(0u32);
863 assert!(strong_count(&a) == 1);
864 let w = a.downgrade();
865 assert!(strong_count(&a) == 1);
866 let b = w.upgrade().expect("");
867 assert!(strong_count(&b) == 2);
868 assert!(strong_count(&a) == 2);
871 assert!(strong_count(&b) == 1);
873 assert!(strong_count(&b) == 2);
874 assert!(strong_count(&c) == 2);
878 fn test_weak_count() {
879 let a = Arc::new(0u32);
880 assert!(strong_count(&a) == 1);
881 assert!(weak_count(&a) == 0);
882 let w = a.downgrade();
883 assert!(strong_count(&a) == 1);
884 assert!(weak_count(&a) == 1);
886 assert!(weak_count(&a) == 2);
889 assert!(strong_count(&a) == 1);
890 assert!(weak_count(&a) == 0);
892 assert!(strong_count(&a) == 2);
893 assert!(weak_count(&a) == 0);
894 let d = c.downgrade();
895 assert!(weak_count(&c) == 1);
896 assert!(strong_count(&c) == 2);
905 let a = Arc::new(5u32);
906 assert_eq!(format!("{:?}", a), "5");
909 // Make sure deriving works with Arc<T>
910 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
911 struct Foo { inner: Arc<i32> }