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
75 use core::prelude::v1::*;
78 use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
80 use core::cmp::Ordering;
81 use core::mem::{align_of_val, size_of_val};
82 use core::intrinsics::{drop_in_place, abort};
84 use core::nonzero::NonZero;
85 use core::ops::{Deref, CoerceUnsized};
87 use core::marker::Unsize;
88 use core::hash::{Hash, Hasher};
89 use core::{usize, isize};
92 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
94 /// An atomically reference counted wrapper for shared state.
98 /// In this example, a large vector of floats is shared between several threads.
99 /// With simple pipes, without `Arc`, a copy would have to be made for each
102 /// When you clone an `Arc<T>`, it will create another pointer to the data and
103 /// increase the reference counter.
106 /// use std::sync::Arc;
110 /// let numbers: Vec<_> = (0..100u32).collect();
111 /// let shared_numbers = Arc::new(numbers);
114 /// let child_numbers = shared_numbers.clone();
116 /// thread::spawn(move || {
117 /// let local_numbers = &child_numbers[..];
119 /// // Work with the local numbers
124 #[unsafe_no_drop_flag]
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub struct Arc<T: ?Sized> {
127 // FIXME #12808: strange name to try to avoid interfering with
128 // field accesses of the contained type via Deref
129 _ptr: NonZero<*mut ArcInner<T>>,
132 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> { }
133 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> { }
135 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
137 /// A weak pointer to an `Arc`.
139 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be
140 /// used to break cycles between `Arc` pointers.
141 #[unsafe_no_drop_flag]
142 #[unstable(feature = "arc_weak",
143 reason = "Weak pointers may not belong in this module.")]
144 pub struct Weak<T: ?Sized> {
145 // FIXME #12808: strange name to try to avoid interfering with
146 // field accesses of the contained type via Deref
147 _ptr: NonZero<*mut ArcInner<T>>,
150 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> { }
151 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> { }
153 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162 struct ArcInner<T: ?Sized> {
163 strong: atomic::AtomicUsize,
165 // the value usize::MAX acts as a sentinel for temporarily "locking" the
166 // ability to upgrade weak pointers or downgrade strong ones; this is used
167 // to avoid races in `make_unique` and `get_mut`.
168 weak: atomic::AtomicUsize,
173 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
174 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
177 /// Constructs a new `Arc<T>`.
182 /// use std::sync::Arc;
184 /// let five = Arc::new(5);
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn new(data: T) -> Arc<T> {
189 // Start the weak pointer count as 1 which is the weak pointer that's
190 // held by all the strong pointers (kinda), see std/rc.rs for more info
191 let x: Box<_> = box ArcInner {
192 strong: atomic::AtomicUsize::new(1),
193 weak: atomic::AtomicUsize::new(1),
196 Arc { _ptr: unsafe { NonZero::new(Box::into_raw(x)) } }
200 impl<T: ?Sized> Arc<T> {
201 /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
206 /// #![feature(arc_weak)]
208 /// use std::sync::Arc;
210 /// let five = Arc::new(5);
212 /// let weak_five = five.downgrade();
214 #[unstable(feature = "arc_weak",
215 reason = "Weak pointers may not belong in this module.")]
216 pub fn downgrade(&self) -> Weak<T> {
218 // This Relaxed is OK because we're checking the value in the CAS
220 let cur = self.inner().weak.load(Relaxed);
222 // check if the weak counter is currently "locked"; if so, spin.
223 if cur == usize::MAX { continue }
225 // NOTE: this code currently ignores the possibility of overflow
226 // into usize::MAX; in general both Rc and Arc need to be adjusted
227 // to deal with overflow.
229 // Unlike with Clone(), we need this to be an Acquire read to
230 // synchronize with the write coming from `is_unique`, so that the
231 // events prior to that write happen before this read.
232 if self.inner().weak.compare_and_swap(cur, cur + 1, Acquire) == cur {
233 return Weak { _ptr: self._ptr }
238 /// Get the number of weak references to this value.
240 #[unstable(feature = "arc_counts")]
241 pub fn weak_count(this: &Arc<T>) -> usize {
242 this.inner().weak.load(SeqCst) - 1
245 /// Get the number of strong references to this value.
247 #[unstable(feature = "arc_counts")]
248 pub fn strong_count(this: &Arc<T>) -> usize {
249 this.inner().strong.load(SeqCst)
253 fn inner(&self) -> &ArcInner<T> {
254 // This unsafety is ok because while this arc is alive we're guaranteed
255 // that the inner pointer is valid. Furthermore, we know that the
256 // `ArcInner` structure itself is `Sync` because the inner data is
257 // `Sync` as well, so we're ok loaning out an immutable pointer to these
259 unsafe { &**self._ptr }
262 // Non-inlined part of `drop`.
264 unsafe fn drop_slow(&mut self) {
265 let ptr = *self._ptr;
267 // Destroy the data at this time, even though we may not free the box
268 // allocation itself (there may still be weak pointers lying around).
269 drop_in_place(&mut (*ptr).data);
271 if self.inner().weak.fetch_sub(1, Release) == 1 {
272 atomic::fence(Acquire);
273 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
278 /// Get the number of weak references to this value.
280 #[unstable(feature = "arc_counts")]
281 #[deprecated(since = "1.2.0", reason = "renamed to Arc::weak_count")]
282 pub fn weak_count<T: ?Sized>(this: &Arc<T>) -> usize { Arc::weak_count(this) }
284 /// Get the number of strong references to this value.
286 #[unstable(feature = "arc_counts")]
287 #[deprecated(since = "1.2.0", reason = "renamed to Arc::strong_count")]
288 pub fn strong_count<T: ?Sized>(this: &Arc<T>) -> usize { Arc::strong_count(this) }
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<T: ?Sized> Clone for Arc<T> {
292 /// Makes a clone of the `Arc<T>`.
294 /// This increases the strong reference count.
299 /// use std::sync::Arc;
301 /// let five = Arc::new(5);
306 fn clone(&self) -> Arc<T> {
307 // Using a relaxed ordering is alright here, as knowledge of the
308 // original reference prevents other threads from erroneously deleting
311 // As explained in the [Boost documentation][1], Increasing the
312 // reference counter can always be done with memory_order_relaxed: New
313 // references to an object can only be formed from an existing
314 // reference, and passing an existing reference from one thread to
315 // another must already provide any required synchronization.
317 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
318 let old_size = self.inner().strong.fetch_add(1, Relaxed);
320 // However we need to guard against massive refcounts in case someone
321 // is `mem::forget`ing Arcs. If we don't do this the count can overflow
322 // and users will use-after free. We racily saturate to `isize::MAX` on
323 // the assumption that there aren't ~2 billion threads incrementing
324 // the reference count at once. This branch will never be taken in
325 // any realistic program.
327 // We abort because such a program is incredibly degenerate, and we
328 // don't care to support it.
329 if old_size > MAX_REFCOUNT {
333 Arc { _ptr: self._ptr }
337 #[stable(feature = "rust1", since = "1.0.0")]
338 impl<T: ?Sized> Deref for Arc<T> {
342 fn deref(&self) -> &T {
347 impl<T: Clone> Arc<T> {
348 /// Make a mutable reference from the given `Arc<T>`.
350 /// This is also referred to as a copy-on-write operation because the inner
351 /// data is cloned if the (strong) reference count is greater than one. If
352 /// we hold the only strong reference, any existing weak references will no
353 /// longer be upgradeable.
358 /// #![feature(arc_unique)]
360 /// use std::sync::Arc;
362 /// let mut five = Arc::new(5);
364 /// let mut_five = Arc::make_unique(&mut five);
367 #[unstable(feature = "arc_unique")]
368 pub fn make_unique(this: &mut Arc<T>) -> &mut T {
369 // Note that we hold both a strong reference and a weak reference.
370 // Thus, releasing our strong reference only will not, by itself, cause
371 // the memory to be deallocated.
373 // Use Acquire to ensure that we see any writes to `weak` that happen
374 // before release writes (i.e., decrements) to `strong`. Since we hold a
375 // weak count, there's no chance the ArcInner itself could be
377 if this.inner().strong.compare_and_swap(1, 0, Acquire) != 1 {
378 // Another srong pointer exists; clone
379 *this = Arc::new((**this).clone());
380 } else if this.inner().weak.load(Relaxed) != 1 {
381 // Relaxed suffices in the above because this is fundamentally an
382 // optimization: we are always racing with weak pointers being
383 // dropped. Worst case, we end up allocated a new Arc unnecessarily.
385 // We removed the last strong ref, but there are additional weak
386 // refs remaining. We'll move the contents to a new Arc, and
387 // invalidate the other weak refs.
389 // Note that it is not possible for the read of `weak` to yield
390 // usize::MAX (i.e., locked), since the weak count can only be
391 // locked by a thread with a strong reference.
393 // Materialize our own implicit weak pointer, so that it can clean
394 // up the ArcInner as needed.
395 let weak = Weak { _ptr: this._ptr };
397 // mark the data itself as already deallocated
399 // there is no data race in the implicit write caused by `read`
400 // here (due to zeroing) because data is no longer accessed by
401 // other threads (due to there being no more strong refs at this
403 let mut swap = Arc::new(ptr::read(&(**weak._ptr).data));
404 mem::swap(this, &mut swap);
408 // We were the sole reference of either kind; bump back up the
410 this.inner().strong.store(1, Release);
413 // As with `get_mut()`, the unsafety is ok because our reference was
414 // either unique to begin with, or became one upon cloning the contents.
416 let inner = &mut **this._ptr;
422 impl<T: ?Sized> Arc<T> {
423 /// Returns a mutable reference to the contained value if the `Arc<T>` is unique.
425 /// Returns `None` if the `Arc<T>` is not unique.
430 /// #![feature(arc_unique, alloc)]
432 /// extern crate alloc;
434 /// use alloc::arc::Arc;
436 /// let mut x = Arc::new(3);
437 /// *Arc::get_mut(&mut x).unwrap() = 4;
438 /// assert_eq!(*x, 4);
440 /// let _y = x.clone();
441 /// assert!(Arc::get_mut(&mut x).is_none());
445 #[unstable(feature = "arc_unique")]
446 pub fn get_mut(this: &mut Arc<T>) -> Option<&mut T> {
447 if this.is_unique() {
448 // This unsafety is ok because we're guaranteed that the pointer
449 // returned is the *only* pointer that will ever be returned to T. Our
450 // reference count is guaranteed to be 1 at this point, and we required
451 // the Arc itself to be `mut`, so we're returning the only possible
452 // reference to the inner data.
454 let inner = &mut **this._ptr;
455 Some(&mut inner.data)
462 /// Determine whether this is the unique reference (including weak refs) to
463 /// the underlying data.
465 /// Note that this requires locking the weak ref count.
466 fn is_unique(&mut self) -> bool {
467 // lock the weak pointer count if we appear to be the sole weak pointer
470 // The acquire label here ensures a happens-before relationship with any
471 // writes to `strong` prior to decrements of the `weak` count (via drop,
472 // which uses Release).
473 if self.inner().weak.compare_and_swap(1, usize::MAX, Acquire) == 1 {
474 // Due to the previous acquire read, this will observe any writes to
475 // `strong` that were due to upgrading weak pointers; only strong
476 // clones remain, which require that the strong count is > 1 anyway.
477 let unique = self.inner().strong.load(Relaxed) == 1;
479 // The release write here synchronizes with a read in `downgrade`,
480 // effectively preventing the above read of `strong` from happening
482 self.inner().weak.store(1, Release); // release the lock
491 #[unstable(feature = "arc_unique")]
492 #[deprecated(since = "1.2", reason = "use Arc::get_mut instead")]
493 pub fn get_mut<T: ?Sized>(this: &mut Arc<T>) -> Option<&mut T> {
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<T: ?Sized> Drop for Arc<T> {
499 /// Drops the `Arc<T>`.
501 /// This will decrement the strong reference count. If the strong reference
502 /// count becomes zero and the only other references are `Weak<T>` ones,
503 /// `drop`s the inner value.
508 /// use std::sync::Arc;
511 /// let five = Arc::new(5);
515 /// drop(five); // explicit drop
518 /// let five = Arc::new(5);
522 /// } // implicit drop
526 // This structure has #[unsafe_no_drop_flag], so this drop glue may run
527 // more than once (but it is guaranteed to be zeroed after the first if
528 // it's run more than once)
529 let ptr = *self._ptr;
530 // if ptr.is_null() { return }
531 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
535 // Because `fetch_sub` is already atomic, we do not need to synchronize
536 // with other threads unless we are going to delete the object. This
537 // same logic applies to the below `fetch_sub` to the `weak` count.
538 if self.inner().strong.fetch_sub(1, Release) != 1 { return }
540 // This fence is needed to prevent reordering of use of the data and
541 // deletion of the data. Because it is marked `Release`, the decreasing
542 // of the reference count synchronizes with this `Acquire` fence. This
543 // means that use of the data happens before decreasing the reference
544 // count, which happens before this fence, which happens before the
545 // deletion of the data.
547 // As explained in the [Boost documentation][1],
549 // > It is important to enforce any possible access to the object in one
550 // > thread (through an existing reference) to *happen before* deleting
551 // > the object in a different thread. This is achieved by a "release"
552 // > operation after dropping a reference (any access to the object
553 // > through this reference must obviously happened before), and an
554 // > "acquire" operation before deleting the object.
556 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
557 atomic::fence(Acquire);
565 #[unstable(feature = "arc_weak",
566 reason = "Weak pointers may not belong in this module.")]
567 impl<T: ?Sized> Weak<T> {
568 /// Upgrades a weak reference to a strong reference.
570 /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
572 /// Returns `None` if there were no strong references and the data was
578 /// #![feature(arc_weak)]
580 /// use std::sync::Arc;
582 /// let five = Arc::new(5);
584 /// let weak_five = five.downgrade();
586 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
588 pub fn upgrade(&self) -> Option<Arc<T>> {
589 // We use a CAS loop to increment the strong count instead of a
590 // fetch_add because once the count hits 0 it must never be above 0.
591 let inner = self.inner();
593 // Relaxed load because any write of 0 that we can observe
594 // leaves the field in a permanently zero state (so a
595 // "stale" read of 0 is fine), and any other value is
596 // confirmed via the CAS below.
597 let n = inner.strong.load(Relaxed);
598 if n == 0 { return None }
600 // Relaxed is valid for the same reason it is on Arc's Clone impl
601 let old = inner.strong.compare_and_swap(n, n + 1, Relaxed);
602 if old == n { return Some(Arc { _ptr: self._ptr }) }
607 fn inner(&self) -> &ArcInner<T> {
608 // See comments above for why this is "safe"
609 unsafe { &**self._ptr }
613 #[unstable(feature = "arc_weak",
614 reason = "Weak pointers may not belong in this module.")]
615 impl<T: ?Sized> Clone for Weak<T> {
616 /// Makes a clone of the `Weak<T>`.
618 /// This increases the weak reference count.
623 /// #![feature(arc_weak)]
625 /// use std::sync::Arc;
627 /// let weak_five = Arc::new(5).downgrade();
629 /// weak_five.clone();
632 fn clone(&self) -> Weak<T> {
633 // See comments in Arc::clone() for why this is relaxed. This can use a
634 // fetch_add (ignoring the lock) because the weak count is only locked
635 // where are *no other* weak pointers in existence. (So we can't be
636 // running this code in that case).
637 let old_size = self.inner().weak.fetch_add(1, Relaxed);
639 // See comments in Arc::clone() for why we do this (for mem::forget).
640 if old_size > MAX_REFCOUNT {
644 return Weak { _ptr: self._ptr }
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl<T: ?Sized> Drop for Weak<T> {
650 /// Drops the `Weak<T>`.
652 /// This will decrement the weak reference count.
657 /// #![feature(arc_weak)]
659 /// use std::sync::Arc;
662 /// let five = Arc::new(5);
663 /// let weak_five = five.downgrade();
667 /// drop(weak_five); // explicit drop
670 /// let five = Arc::new(5);
671 /// let weak_five = five.downgrade();
675 /// } // implicit drop
678 let ptr = *self._ptr;
680 // see comments above for why this check is here
681 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
685 // If we find out that we were the last weak pointer, then its time to
686 // deallocate the data entirely. See the discussion in Arc::drop() about
687 // the memory orderings
689 // It's not necessary to check for the locked state here, because the
690 // weak count can only be locked if there was precisely one weak ref,
691 // meaning that drop could only subsequently run ON that remaining weak
692 // ref, which can only happen after the lock is released.
693 if self.inner().weak.fetch_sub(1, Release) == 1 {
694 atomic::fence(Acquire);
695 unsafe { deallocate(ptr as *mut u8,
697 align_of_val(&*ptr)) }
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
704 /// Equality for two `Arc<T>`s.
706 /// Two `Arc<T>`s are equal if their inner value are equal.
711 /// use std::sync::Arc;
713 /// let five = Arc::new(5);
715 /// five == Arc::new(5);
717 fn eq(&self, other: &Arc<T>) -> bool { *(*self) == *(*other) }
719 /// Inequality for two `Arc<T>`s.
721 /// Two `Arc<T>`s are unequal if their inner value are unequal.
726 /// use std::sync::Arc;
728 /// let five = Arc::new(5);
730 /// five != Arc::new(5);
732 fn ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) }
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
736 /// Partial comparison for two `Arc<T>`s.
738 /// The two are compared by calling `partial_cmp()` on their inner values.
743 /// use std::sync::Arc;
745 /// let five = Arc::new(5);
747 /// five.partial_cmp(&Arc::new(5));
749 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
750 (**self).partial_cmp(&**other)
753 /// Less-than comparison for two `Arc<T>`s.
755 /// The two are compared by calling `<` on their inner values.
760 /// use std::sync::Arc;
762 /// let five = Arc::new(5);
764 /// five < Arc::new(5);
766 fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) }
768 /// 'Less-than or equal to' comparison for two `Arc<T>`s.
770 /// The two are compared by calling `<=` on their inner values.
775 /// use std::sync::Arc;
777 /// let five = Arc::new(5);
779 /// five <= Arc::new(5);
781 fn le(&self, other: &Arc<T>) -> bool { *(*self) <= *(*other) }
783 /// Greater-than comparison for two `Arc<T>`s.
785 /// The two are compared by calling `>` on their inner values.
790 /// use std::sync::Arc;
792 /// let five = Arc::new(5);
794 /// five > Arc::new(5);
796 fn gt(&self, other: &Arc<T>) -> bool { *(*self) > *(*other) }
798 /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
800 /// The two are compared by calling `>=` on their inner values.
805 /// use std::sync::Arc;
807 /// let five = Arc::new(5);
809 /// five >= Arc::new(5);
811 fn ge(&self, other: &Arc<T>) -> bool { *(*self) >= *(*other) }
813 #[stable(feature = "rust1", since = "1.0.0")]
814 impl<T: ?Sized + Ord> Ord for Arc<T> {
815 fn cmp(&self, other: &Arc<T>) -> Ordering { (**self).cmp(&**other) }
817 #[stable(feature = "rust1", since = "1.0.0")]
818 impl<T: ?Sized + Eq> Eq for Arc<T> {}
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
822 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
823 fmt::Display::fmt(&**self, f)
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
829 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
830 fmt::Debug::fmt(&**self, f)
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl<T> fmt::Pointer for Arc<T> {
836 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
837 fmt::Pointer::fmt(&*self._ptr, f)
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<T: Default> Default for Arc<T> {
843 #[stable(feature = "rust1", since = "1.0.0")]
844 fn default() -> Arc<T> { Arc::new(Default::default()) }
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<T: ?Sized + Hash> Hash for Arc<T> {
849 fn hash<H: Hasher>(&self, state: &mut H) {
856 use std::clone::Clone;
857 use std::sync::mpsc::channel;
860 use std::option::Option;
861 use std::option::Option::{Some, None};
862 use std::sync::atomic;
863 use std::sync::atomic::Ordering::{Acquire, SeqCst};
866 use super::{Arc, Weak, get_mut, weak_count, strong_count};
867 use std::sync::Mutex;
869 struct Canary(*mut atomic::AtomicUsize);
877 (*c).fetch_add(1, SeqCst);
885 fn manually_share_arc() {
886 let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
887 let arc_v = Arc::new(v);
889 let (tx, rx) = channel();
891 let _t = thread::spawn(move || {
892 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
893 assert_eq!((*arc_v)[3], 4);
896 tx.send(arc_v.clone()).unwrap();
898 assert_eq!((*arc_v)[2], 3);
899 assert_eq!((*arc_v)[4], 5);
903 fn test_arc_get_mut() {
905 let mut x = Arc::new(3);
906 *get_mut(&mut x).unwrap() = 4;
909 assert!(get_mut(&mut x).is_none());
911 assert!(get_mut(&mut x).is_some());
912 let _w = x.downgrade();
913 assert!(get_mut(&mut x).is_none());
918 fn test_cowarc_clone_make_unique() {
920 let mut cow0 = Arc::new(75);
921 let mut cow1 = cow0.clone();
922 let mut cow2 = cow1.clone();
924 assert!(75 == *Arc::make_unique(&mut cow0));
925 assert!(75 == *Arc::make_unique(&mut cow1));
926 assert!(75 == *Arc::make_unique(&mut cow2));
928 *Arc::make_unique(&mut cow0) += 1;
929 *Arc::make_unique(&mut cow1) += 2;
930 *Arc::make_unique(&mut cow2) += 3;
932 assert!(76 == *cow0);
933 assert!(77 == *cow1);
934 assert!(78 == *cow2);
936 // none should point to the same backing memory
937 assert!(*cow0 != *cow1);
938 assert!(*cow0 != *cow2);
939 assert!(*cow1 != *cow2);
944 fn test_cowarc_clone_unique2() {
945 let mut cow0 = Arc::new(75);
946 let cow1 = cow0.clone();
947 let cow2 = cow1.clone();
949 assert!(75 == *cow0);
950 assert!(75 == *cow1);
951 assert!(75 == *cow2);
954 *Arc::make_unique(&mut cow0) += 1;
957 assert!(76 == *cow0);
958 assert!(75 == *cow1);
959 assert!(75 == *cow2);
961 // cow1 and cow2 should share the same contents
962 // cow0 should have a unique reference
963 assert!(*cow0 != *cow1);
964 assert!(*cow0 != *cow2);
965 assert!(*cow1 == *cow2);
969 fn test_cowarc_clone_weak() {
970 let mut cow0 = Arc::new(75);
971 let cow1_weak = cow0.downgrade();
973 assert!(75 == *cow0);
974 assert!(75 == *cow1_weak.upgrade().unwrap());
977 *Arc::make_unique(&mut cow0) += 1;
980 assert!(76 == *cow0);
981 assert!(cow1_weak.upgrade().is_none());
987 let y = x.downgrade();
988 assert!(y.upgrade().is_some());
994 let y = x.downgrade();
996 assert!(y.upgrade().is_none());
1000 fn weak_self_cyclic() {
1002 x: Mutex<Option<Weak<Cycle>>>
1005 let a = Arc::new(Cycle { x: Mutex::new(None) });
1006 let b = a.clone().downgrade();
1007 *a.x.lock().unwrap() = Some(b);
1009 // hopefully we don't double-free (or leak)...
1014 let mut canary = atomic::AtomicUsize::new(0);
1015 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1017 assert!(canary.load(Acquire) == 1);
1021 fn drop_arc_weak() {
1022 let mut canary = atomic::AtomicUsize::new(0);
1023 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1024 let arc_weak = arc.downgrade();
1025 assert!(canary.load(Acquire) == 0);
1027 assert!(canary.load(Acquire) == 1);
1032 fn test_strong_count() {
1033 let a = Arc::new(0u32);
1034 assert!(strong_count(&a) == 1);
1035 let w = a.downgrade();
1036 assert!(strong_count(&a) == 1);
1037 let b = w.upgrade().expect("");
1038 assert!(strong_count(&b) == 2);
1039 assert!(strong_count(&a) == 2);
1042 assert!(strong_count(&b) == 1);
1044 assert!(strong_count(&b) == 2);
1045 assert!(strong_count(&c) == 2);
1049 fn test_weak_count() {
1050 let a = Arc::new(0u32);
1051 assert!(strong_count(&a) == 1);
1052 assert!(weak_count(&a) == 0);
1053 let w = a.downgrade();
1054 assert!(strong_count(&a) == 1);
1055 assert!(weak_count(&a) == 1);
1057 assert!(weak_count(&a) == 2);
1060 assert!(strong_count(&a) == 1);
1061 assert!(weak_count(&a) == 0);
1063 assert!(strong_count(&a) == 2);
1064 assert!(weak_count(&a) == 0);
1065 let d = c.downgrade();
1066 assert!(weak_count(&c) == 1);
1067 assert!(strong_count(&c) == 2);
1076 let a = Arc::new(5u32);
1077 assert_eq!(format!("{:?}", a), "5");
1080 // Make sure deriving works with Arc<T>
1081 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1082 struct Foo { inner: Arc<i32> }
1086 let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1087 assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1088 let y = x.clone().downgrade();
1090 assert!(y.upgrade().is_none());