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 threads:
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 threads 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
74 use core::sync::atomic;
75 use core::sync::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
78 use core::cmp::Ordering;
79 use core::mem::{align_of_val, size_of_val};
80 use core::intrinsics::abort;
82 use core::mem::uninitialized;
85 use core::ops::CoerceUnsized;
86 use core::ptr::{self, Shared};
88 use core::marker::Unsize;
89 use core::hash::{Hash, Hasher};
90 use core::{usize, isize};
91 use core::convert::From;
94 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
96 /// An atomically reference counted wrapper for shared state.
100 /// In this example, a large vector is shared between several threads.
101 /// With simple pipes, without `Arc`, a copy would have to be made for each
104 /// When you clone an `Arc<T>`, it will create another pointer to the data and
105 /// increase the reference counter.
108 /// use std::sync::Arc;
112 /// let numbers: Vec<_> = (0..100u32).collect();
113 /// let shared_numbers = Arc::new(numbers);
116 /// let child_numbers = shared_numbers.clone();
118 /// thread::spawn(move || {
119 /// let local_numbers = &child_numbers[..];
121 /// // Work with the local numbers
126 #[unsafe_no_drop_flag]
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub struct Arc<T: ?Sized> {
129 // FIXME #12808: strange name to try to avoid interfering with
130 // field accesses of the contained type via Deref
131 _ptr: Shared<ArcInner<T>>,
134 #[stable(feature = "rust1", since = "1.0.0")]
135 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
136 #[stable(feature = "rust1", since = "1.0.0")]
137 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
139 // remove cfg after new snapshot
141 #[unstable(feature = "coerce_unsized", issue = "27732")]
142 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
144 /// A weak pointer to an `Arc`.
146 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be
147 /// used to break cycles between `Arc` pointers.
148 #[unsafe_no_drop_flag]
149 #[stable(feature = "arc_weak", since = "1.4.0")]
150 pub struct Weak<T: ?Sized> {
151 // FIXME #12808: strange name to try to avoid interfering with
152 // field accesses of the contained type via Deref
153 _ptr: Shared<ArcInner<T>>,
156 #[stable(feature = "rust1", since = "1.0.0")]
157 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
158 #[stable(feature = "rust1", since = "1.0.0")]
159 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
161 // remove cfg after new snapshot
163 #[unstable(feature = "coerce_unsized", issue = "27732")]
164 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
166 #[stable(feature = "rust1", since = "1.0.0")]
167 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
173 struct ArcInner<T: ?Sized> {
174 strong: atomic::AtomicUsize,
176 // the value usize::MAX acts as a sentinel for temporarily "locking" the
177 // ability to upgrade weak pointers or downgrade strong ones; this is used
178 // to avoid races in `make_mut` and `get_mut`.
179 weak: atomic::AtomicUsize,
184 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
185 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
188 /// Constructs a new `Arc<T>`.
193 /// use std::sync::Arc;
195 /// let five = Arc::new(5);
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn new(data: T) -> Arc<T> {
200 // Start the weak pointer count as 1 which is the weak pointer that's
201 // held by all the strong pointers (kinda), see std/rc.rs for more info
202 let x: Box<_> = box ArcInner {
203 strong: atomic::AtomicUsize::new(1),
204 weak: atomic::AtomicUsize::new(1),
207 Arc { _ptr: unsafe { Shared::new(Box::into_raw(x)) } }
210 /// Unwraps the contained value if the `Arc<T>` has only one strong reference.
211 /// This will succeed even if there are outstanding weak references.
213 /// Otherwise, an `Err` is returned with the same `Arc<T>`.
218 /// use std::sync::Arc;
220 /// let x = Arc::new(3);
221 /// assert_eq!(Arc::try_unwrap(x), Ok(3));
223 /// let x = Arc::new(4);
224 /// let _y = x.clone();
225 /// assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
228 #[stable(feature = "arc_unique", since = "1.4.0")]
229 pub fn try_unwrap(this: Self) -> Result<T, Self> {
230 // See `drop` for why all these atomics are like this
231 if this.inner().strong.compare_and_swap(1, 0, Release) != 1 {
235 atomic::fence(Acquire);
238 let ptr = *this._ptr;
239 let elem = ptr::read(&(*ptr).data);
241 // Make a weak pointer to clean up the implicit strong-weak reference
242 let _weak = Weak { _ptr: this._ptr };
250 impl<T: ?Sized> Arc<T> {
251 /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
256 /// use std::sync::Arc;
258 /// let five = Arc::new(5);
260 /// let weak_five = Arc::downgrade(&five);
262 #[stable(feature = "arc_weak", since = "1.4.0")]
263 pub fn downgrade(this: &Self) -> Weak<T> {
265 // This Relaxed is OK because we're checking the value in the CAS
267 let cur = this.inner().weak.load(Relaxed);
269 // check if the weak counter is currently "locked"; if so, spin.
270 if cur == usize::MAX {
274 // NOTE: this code currently ignores the possibility of overflow
275 // into usize::MAX; in general both Rc and Arc need to be adjusted
276 // to deal with overflow.
278 // Unlike with Clone(), we need this to be an Acquire read to
279 // synchronize with the write coming from `is_unique`, so that the
280 // events prior to that write happen before this read.
281 if this.inner().weak.compare_and_swap(cur, cur + 1, Acquire) == cur {
282 return Weak { _ptr: this._ptr };
287 /// Get the number of weak references to this value.
289 #[unstable(feature = "arc_counts", reason = "not clearly useful, and racy",
291 pub fn weak_count(this: &Self) -> usize {
292 this.inner().weak.load(SeqCst) - 1
295 /// Get the number of strong references to this value.
297 #[unstable(feature = "arc_counts", reason = "not clearly useful, and racy",
299 pub fn strong_count(this: &Self) -> usize {
300 this.inner().strong.load(SeqCst)
304 fn inner(&self) -> &ArcInner<T> {
305 // This unsafety is ok because while this arc is alive we're guaranteed
306 // that the inner pointer is valid. Furthermore, we know that the
307 // `ArcInner` structure itself is `Sync` because the inner data is
308 // `Sync` as well, so we're ok loaning out an immutable pointer to these
310 unsafe { &**self._ptr }
313 // Non-inlined part of `drop`.
315 unsafe fn drop_slow(&mut self) {
316 let ptr = *self._ptr;
318 // Destroy the data at this time, even though we may not free the box
319 // allocation itself (there may still be weak pointers lying around).
320 ptr::drop_in_place(&mut (*ptr).data);
322 if self.inner().weak.fetch_sub(1, Release) == 1 {
323 atomic::fence(Acquire);
324 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl<T: ?Sized> Clone for Arc<T> {
331 /// Makes a clone of the `Arc<T>`.
333 /// This increases the strong reference count.
338 /// use std::sync::Arc;
340 /// let five = Arc::new(5);
345 fn clone(&self) -> Arc<T> {
346 // Using a relaxed ordering is alright here, as knowledge of the
347 // original reference prevents other threads from erroneously deleting
350 // As explained in the [Boost documentation][1], Increasing the
351 // reference counter can always be done with memory_order_relaxed: New
352 // references to an object can only be formed from an existing
353 // reference, and passing an existing reference from one thread to
354 // another must already provide any required synchronization.
356 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
357 let old_size = self.inner().strong.fetch_add(1, Relaxed);
359 // However we need to guard against massive refcounts in case someone
360 // is `mem::forget`ing Arcs. If we don't do this the count can overflow
361 // and users will use-after free. We racily saturate to `isize::MAX` on
362 // the assumption that there aren't ~2 billion threads incrementing
363 // the reference count at once. This branch will never be taken in
364 // any realistic program.
366 // We abort because such a program is incredibly degenerate, and we
367 // don't care to support it.
368 if old_size > MAX_REFCOUNT {
374 Arc { _ptr: self._ptr }
378 #[stable(feature = "rust1", since = "1.0.0")]
379 impl<T: ?Sized> Deref for Arc<T> {
383 fn deref(&self) -> &T {
388 impl<T: Clone> Arc<T> {
389 /// Make a mutable reference into the given `Arc<T>` by cloning the inner
390 /// data if the `Arc<T>` doesn't have one strong reference and no weak
393 /// This is also referred to as a copy-on-write.
398 /// use std::sync::Arc;
400 /// let mut data = Arc::new(5);
402 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
403 /// let mut other_data = data.clone(); // Won't clone inner data
404 /// *Arc::make_mut(&mut data) += 1; // Clones inner data
405 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
406 /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything
408 /// // Note: data and other_data now point to different numbers
409 /// assert_eq!(*data, 8);
410 /// assert_eq!(*other_data, 12);
414 #[stable(feature = "arc_unique", since = "1.4.0")]
415 pub fn make_mut(this: &mut Self) -> &mut T {
416 // Note that we hold both a strong reference and a weak reference.
417 // Thus, releasing our strong reference only will not, by itself, cause
418 // the memory to be deallocated.
420 // Use Acquire to ensure that we see any writes to `weak` that happen
421 // before release writes (i.e., decrements) to `strong`. Since we hold a
422 // weak count, there's no chance the ArcInner itself could be
424 if this.inner().strong.compare_and_swap(1, 0, Acquire) != 1 {
425 // Another strong pointer exists; clone
426 *this = Arc::new((**this).clone());
427 } else if this.inner().weak.load(Relaxed) != 1 {
428 // Relaxed suffices in the above because this is fundamentally an
429 // optimization: we are always racing with weak pointers being
430 // dropped. Worst case, we end up allocated a new Arc unnecessarily.
432 // We removed the last strong ref, but there are additional weak
433 // refs remaining. We'll move the contents to a new Arc, and
434 // invalidate the other weak refs.
436 // Note that it is not possible for the read of `weak` to yield
437 // usize::MAX (i.e., locked), since the weak count can only be
438 // locked by a thread with a strong reference.
440 // Materialize our own implicit weak pointer, so that it can clean
441 // up the ArcInner as needed.
442 let weak = Weak { _ptr: this._ptr };
444 // mark the data itself as already deallocated
446 // there is no data race in the implicit write caused by `read`
447 // here (due to zeroing) because data is no longer accessed by
448 // other threads (due to there being no more strong refs at this
450 let mut swap = Arc::new(ptr::read(&(**weak._ptr).data));
451 mem::swap(this, &mut swap);
455 // We were the sole reference of either kind; bump back up the
457 this.inner().strong.store(1, Release);
460 // As with `get_mut()`, the unsafety is ok because our reference was
461 // either unique to begin with, or became one upon cloning the contents.
463 let inner = &mut **this._ptr;
469 impl<T: ?Sized> Arc<T> {
470 /// Returns a mutable reference to the contained value if the `Arc<T>` has
471 /// one strong reference and no weak references.
476 /// use std::sync::Arc;
478 /// let mut x = Arc::new(3);
479 /// *Arc::get_mut(&mut x).unwrap() = 4;
480 /// assert_eq!(*x, 4);
482 /// let _y = x.clone();
483 /// assert!(Arc::get_mut(&mut x).is_none());
486 #[stable(feature = "arc_unique", since = "1.4.0")]
487 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
488 if this.is_unique() {
489 // This unsafety is ok because we're guaranteed that the pointer
490 // returned is the *only* pointer that will ever be returned to T. Our
491 // reference count is guaranteed to be 1 at this point, and we required
492 // the Arc itself to be `mut`, so we're returning the only possible
493 // reference to the inner data.
495 let inner = &mut **this._ptr;
496 Some(&mut inner.data)
503 /// Determine whether this is the unique reference (including weak refs) to
504 /// the underlying data.
506 /// Note that this requires locking the weak ref count.
507 fn is_unique(&mut self) -> bool {
508 // lock the weak pointer count if we appear to be the sole weak pointer
511 // The acquire label here ensures a happens-before relationship with any
512 // writes to `strong` prior to decrements of the `weak` count (via drop,
513 // which uses Release).
514 if self.inner().weak.compare_and_swap(1, usize::MAX, Acquire) == 1 {
515 // Due to the previous acquire read, this will observe any writes to
516 // `strong` that were due to upgrading weak pointers; only strong
517 // clones remain, which require that the strong count is > 1 anyway.
518 let unique = self.inner().strong.load(Relaxed) == 1;
520 // The release write here synchronizes with a read in `downgrade`,
521 // effectively preventing the above read of `strong` from happening
523 self.inner().weak.store(1, Release); // release the lock
531 #[stable(feature = "rust1", since = "1.0.0")]
532 impl<T: ?Sized> Drop for Arc<T> {
533 /// Drops the `Arc<T>`.
535 /// This will decrement the strong reference count. If the strong reference
536 /// count becomes zero and the only other references are `Weak<T>` ones,
537 /// `drop`s the inner value.
542 /// use std::sync::Arc;
545 /// let five = Arc::new(5);
549 /// drop(five); // explicit drop
552 /// let five = Arc::new(5);
556 /// } // implicit drop
558 #[unsafe_destructor_blind_to_params]
561 // This structure has #[unsafe_no_drop_flag], so this drop glue may run
562 // more than once (but it is guaranteed to be zeroed after the first if
563 // it's run more than once)
564 let ptr = *self._ptr;
565 // if ptr.is_null() { return }
566 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
570 // Because `fetch_sub` is already atomic, we do not need to synchronize
571 // with other threads unless we are going to delete the object. This
572 // same logic applies to the below `fetch_sub` to the `weak` count.
573 if self.inner().strong.fetch_sub(1, Release) != 1 {
577 // This fence is needed to prevent reordering of use of the data and
578 // deletion of the data. Because it is marked `Release`, the decreasing
579 // of the reference count synchronizes with this `Acquire` fence. This
580 // means that use of the data happens before decreasing the reference
581 // count, which happens before this fence, which happens before the
582 // deletion of the data.
584 // As explained in the [Boost documentation][1],
586 // > It is important to enforce any possible access to the object in one
587 // > thread (through an existing reference) to *happen before* deleting
588 // > the object in a different thread. This is achieved by a "release"
589 // > operation after dropping a reference (any access to the object
590 // > through this reference must obviously happened before), and an
591 // > "acquire" operation before deleting the object.
593 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
594 atomic::fence(Acquire);
602 impl<T: ?Sized> Weak<T> {
603 /// Upgrades a weak reference to a strong reference.
605 /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
607 /// Returns `None` if there were no strong references and the data was
613 /// use std::sync::Arc;
615 /// let five = Arc::new(5);
617 /// let weak_five = Arc::downgrade(&five);
619 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
621 #[stable(feature = "arc_weak", since = "1.4.0")]
622 pub fn upgrade(&self) -> Option<Arc<T>> {
623 // We use a CAS loop to increment the strong count instead of a
624 // fetch_add because once the count hits 0 it must never be above 0.
625 let inner = self.inner();
627 // Relaxed load because any write of 0 that we can observe
628 // leaves the field in a permanently zero state (so a
629 // "stale" read of 0 is fine), and any other value is
630 // confirmed via the CAS below.
631 let n = inner.strong.load(Relaxed);
636 // See comments in `Arc::clone` for why we do this (for `mem::forget`).
637 if n > MAX_REFCOUNT {
641 // Relaxed is valid for the same reason it is on Arc's Clone impl
642 let old = inner.strong.compare_and_swap(n, n + 1, Relaxed);
644 return Some(Arc { _ptr: self._ptr });
650 fn inner(&self) -> &ArcInner<T> {
651 // See comments above for why this is "safe"
652 unsafe { &**self._ptr }
656 #[stable(feature = "arc_weak", since = "1.4.0")]
657 impl<T: ?Sized> Clone for Weak<T> {
658 /// Makes a clone of the `Weak<T>`.
660 /// This increases the weak reference count.
665 /// use std::sync::Arc;
667 /// let weak_five = Arc::downgrade(&Arc::new(5));
669 /// weak_five.clone();
672 fn clone(&self) -> Weak<T> {
673 // See comments in Arc::clone() for why this is relaxed. This can use a
674 // fetch_add (ignoring the lock) because the weak count is only locked
675 // where are *no other* weak pointers in existence. (So we can't be
676 // running this code in that case).
677 let old_size = self.inner().weak.fetch_add(1, Relaxed);
679 // See comments in Arc::clone() for why we do this (for mem::forget).
680 if old_size > MAX_REFCOUNT {
686 return Weak { _ptr: self._ptr };
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl<T: ?Sized> Drop for Weak<T> {
692 /// Drops the `Weak<T>`.
694 /// This will decrement the weak reference count.
699 /// use std::sync::Arc;
702 /// let five = Arc::new(5);
703 /// let weak_five = Arc::downgrade(&five);
707 /// drop(weak_five); // explicit drop
710 /// let five = Arc::new(5);
711 /// let weak_five = Arc::downgrade(&five);
715 /// } // implicit drop
718 let ptr = *self._ptr;
720 // see comments above for why this check is here
721 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
725 // If we find out that we were the last weak pointer, then its time to
726 // deallocate the data entirely. See the discussion in Arc::drop() about
727 // the memory orderings
729 // It's not necessary to check for the locked state here, because the
730 // weak count can only be locked if there was precisely one weak ref,
731 // meaning that drop could only subsequently run ON that remaining weak
732 // ref, which can only happen after the lock is released.
733 if self.inner().weak.fetch_sub(1, Release) == 1 {
734 atomic::fence(Acquire);
735 unsafe { deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr)) }
740 #[stable(feature = "rust1", since = "1.0.0")]
741 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
742 /// Equality for two `Arc<T>`s.
744 /// Two `Arc<T>`s are equal if their inner value are equal.
749 /// use std::sync::Arc;
751 /// let five = Arc::new(5);
753 /// five == Arc::new(5);
755 fn eq(&self, other: &Arc<T>) -> bool {
756 *(*self) == *(*other)
759 /// Inequality for two `Arc<T>`s.
761 /// Two `Arc<T>`s are unequal if their inner value are unequal.
766 /// use std::sync::Arc;
768 /// let five = Arc::new(5);
770 /// five != Arc::new(5);
772 fn ne(&self, other: &Arc<T>) -> bool {
773 *(*self) != *(*other)
776 #[stable(feature = "rust1", since = "1.0.0")]
777 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
778 /// Partial comparison for two `Arc<T>`s.
780 /// The two are compared by calling `partial_cmp()` on their inner values.
785 /// use std::sync::Arc;
787 /// let five = Arc::new(5);
789 /// five.partial_cmp(&Arc::new(5));
791 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
792 (**self).partial_cmp(&**other)
795 /// Less-than comparison for two `Arc<T>`s.
797 /// The two are compared by calling `<` on their inner values.
802 /// use std::sync::Arc;
804 /// let five = Arc::new(5);
806 /// five < Arc::new(5);
808 fn lt(&self, other: &Arc<T>) -> bool {
812 /// 'Less-than or equal to' comparison for two `Arc<T>`s.
814 /// The two are compared by calling `<=` on their inner values.
819 /// use std::sync::Arc;
821 /// let five = Arc::new(5);
823 /// five <= Arc::new(5);
825 fn le(&self, other: &Arc<T>) -> bool {
826 *(*self) <= *(*other)
829 /// Greater-than comparison for two `Arc<T>`s.
831 /// The two are compared by calling `>` on their inner values.
836 /// use std::sync::Arc;
838 /// let five = Arc::new(5);
840 /// five > Arc::new(5);
842 fn gt(&self, other: &Arc<T>) -> bool {
846 /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
848 /// The two are compared by calling `>=` on their inner values.
853 /// use std::sync::Arc;
855 /// let five = Arc::new(5);
857 /// five >= Arc::new(5);
859 fn ge(&self, other: &Arc<T>) -> bool {
860 *(*self) >= *(*other)
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl<T: ?Sized + Ord> Ord for Arc<T> {
865 fn cmp(&self, other: &Arc<T>) -> Ordering {
866 (**self).cmp(&**other)
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl<T: ?Sized + Eq> Eq for Arc<T> {}
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
874 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
875 fmt::Display::fmt(&**self, f)
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
881 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
882 fmt::Debug::fmt(&**self, f)
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl<T> fmt::Pointer for Arc<T> {
888 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
889 fmt::Pointer::fmt(&*self._ptr, f)
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<T: Default> Default for Arc<T> {
895 fn default() -> Arc<T> {
896 Arc::new(Default::default())
900 #[stable(feature = "rust1", since = "1.0.0")]
901 impl<T: ?Sized + Hash> Hash for Arc<T> {
902 fn hash<H: Hasher>(&self, state: &mut H) {
907 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
908 impl<T> From<T> for Arc<T> {
909 fn from(t: T) -> Self {
915 /// Constructs a new `Weak<T>` without an accompanying instance of T.
917 /// This allocates memory for T, but does not initialize it. Calling
918 /// Weak<T>::upgrade() on the return value always gives None.
923 /// #![feature(downgraded_weak)]
925 /// use std::sync::Weak;
927 /// let empty: Weak<i64> = Weak::new();
929 #[unstable(feature = "downgraded_weak",
930 reason = "recently added",
932 pub fn new() -> Weak<T> {
934 Weak { _ptr: Shared::new(Box::into_raw(box ArcInner {
935 strong: atomic::AtomicUsize::new(0),
936 weak: atomic::AtomicUsize::new(1),
937 data: uninitialized(),
945 use std::clone::Clone;
946 use std::sync::mpsc::channel;
949 use std::option::Option;
950 use std::option::Option::{Some, None};
951 use std::sync::atomic;
952 use std::sync::atomic::Ordering::{Acquire, SeqCst};
955 use super::{Arc, Weak};
956 use std::sync::Mutex;
957 use std::convert::From;
959 struct Canary(*mut atomic::AtomicUsize);
961 impl Drop for Canary {
966 (*c).fetch_add(1, SeqCst);
974 fn manually_share_arc() {
975 let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
976 let arc_v = Arc::new(v);
978 let (tx, rx) = channel();
980 let _t = thread::spawn(move || {
981 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
982 assert_eq!((*arc_v)[3], 4);
985 tx.send(arc_v.clone()).unwrap();
987 assert_eq!((*arc_v)[2], 3);
988 assert_eq!((*arc_v)[4], 5);
992 fn test_arc_get_mut() {
993 let mut x = Arc::new(3);
994 *Arc::get_mut(&mut x).unwrap() = 4;
997 assert!(Arc::get_mut(&mut x).is_none());
999 assert!(Arc::get_mut(&mut x).is_some());
1000 let _w = Arc::downgrade(&x);
1001 assert!(Arc::get_mut(&mut x).is_none());
1006 let x = Arc::new(3);
1007 assert_eq!(Arc::try_unwrap(x), Ok(3));
1008 let x = Arc::new(4);
1010 assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
1011 let x = Arc::new(5);
1012 let _w = Arc::downgrade(&x);
1013 assert_eq!(Arc::try_unwrap(x), Ok(5));
1017 fn test_cowarc_clone_make_mut() {
1018 let mut cow0 = Arc::new(75);
1019 let mut cow1 = cow0.clone();
1020 let mut cow2 = cow1.clone();
1022 assert!(75 == *Arc::make_mut(&mut cow0));
1023 assert!(75 == *Arc::make_mut(&mut cow1));
1024 assert!(75 == *Arc::make_mut(&mut cow2));
1026 *Arc::make_mut(&mut cow0) += 1;
1027 *Arc::make_mut(&mut cow1) += 2;
1028 *Arc::make_mut(&mut cow2) += 3;
1030 assert!(76 == *cow0);
1031 assert!(77 == *cow1);
1032 assert!(78 == *cow2);
1034 // none should point to the same backing memory
1035 assert!(*cow0 != *cow1);
1036 assert!(*cow0 != *cow2);
1037 assert!(*cow1 != *cow2);
1041 fn test_cowarc_clone_unique2() {
1042 let mut cow0 = Arc::new(75);
1043 let cow1 = cow0.clone();
1044 let cow2 = cow1.clone();
1046 assert!(75 == *cow0);
1047 assert!(75 == *cow1);
1048 assert!(75 == *cow2);
1050 *Arc::make_mut(&mut cow0) += 1;
1051 assert!(76 == *cow0);
1052 assert!(75 == *cow1);
1053 assert!(75 == *cow2);
1055 // cow1 and cow2 should share the same contents
1056 // cow0 should have a unique reference
1057 assert!(*cow0 != *cow1);
1058 assert!(*cow0 != *cow2);
1059 assert!(*cow1 == *cow2);
1063 fn test_cowarc_clone_weak() {
1064 let mut cow0 = Arc::new(75);
1065 let cow1_weak = Arc::downgrade(&cow0);
1067 assert!(75 == *cow0);
1068 assert!(75 == *cow1_weak.upgrade().unwrap());
1070 *Arc::make_mut(&mut cow0) += 1;
1072 assert!(76 == *cow0);
1073 assert!(cow1_weak.upgrade().is_none());
1078 let x = Arc::new(5);
1079 let y = Arc::downgrade(&x);
1080 assert!(y.upgrade().is_some());
1085 let x = Arc::new(5);
1086 let y = Arc::downgrade(&x);
1088 assert!(y.upgrade().is_none());
1092 fn weak_self_cyclic() {
1094 x: Mutex<Option<Weak<Cycle>>>,
1097 let a = Arc::new(Cycle { x: Mutex::new(None) });
1098 let b = Arc::downgrade(&a.clone());
1099 *a.x.lock().unwrap() = Some(b);
1101 // hopefully we don't double-free (or leak)...
1106 let mut canary = atomic::AtomicUsize::new(0);
1107 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1109 assert!(canary.load(Acquire) == 1);
1113 fn drop_arc_weak() {
1114 let mut canary = atomic::AtomicUsize::new(0);
1115 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1116 let arc_weak = Arc::downgrade(&arc);
1117 assert!(canary.load(Acquire) == 0);
1119 assert!(canary.load(Acquire) == 1);
1124 fn test_strong_count() {
1125 let a = Arc::new(0u32);
1126 assert!(Arc::strong_count(&a) == 1);
1127 let w = Arc::downgrade(&a);
1128 assert!(Arc::strong_count(&a) == 1);
1129 let b = w.upgrade().expect("");
1130 assert!(Arc::strong_count(&b) == 2);
1131 assert!(Arc::strong_count(&a) == 2);
1134 assert!(Arc::strong_count(&b) == 1);
1136 assert!(Arc::strong_count(&b) == 2);
1137 assert!(Arc::strong_count(&c) == 2);
1141 fn test_weak_count() {
1142 let a = Arc::new(0u32);
1143 assert!(Arc::strong_count(&a) == 1);
1144 assert!(Arc::weak_count(&a) == 0);
1145 let w = Arc::downgrade(&a);
1146 assert!(Arc::strong_count(&a) == 1);
1147 assert!(Arc::weak_count(&a) == 1);
1149 assert!(Arc::weak_count(&a) == 2);
1152 assert!(Arc::strong_count(&a) == 1);
1153 assert!(Arc::weak_count(&a) == 0);
1155 assert!(Arc::strong_count(&a) == 2);
1156 assert!(Arc::weak_count(&a) == 0);
1157 let d = Arc::downgrade(&c);
1158 assert!(Arc::weak_count(&c) == 1);
1159 assert!(Arc::strong_count(&c) == 2);
1168 let a = Arc::new(5u32);
1169 assert_eq!(format!("{:?}", a), "5");
1172 // Make sure deriving works with Arc<T>
1173 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1180 let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1181 assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1182 let y = Arc::downgrade(&x.clone());
1184 assert!(y.upgrade().is_none());
1188 fn test_from_owned() {
1190 let foo_arc = Arc::from(foo);
1191 assert!(123 == *foo_arc);
1195 fn test_new_weak() {
1196 let foo: Weak<usize> = Weak::new();
1197 assert!(foo.upgrade().is_none());
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
1203 fn borrow(&self) -> &T {
1208 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1209 impl<T: ?Sized> AsRef<T> for Arc<T> {
1210 fn as_ref(&self) -> &T {