1 #![stable(feature = "rust1", since = "1.0.0")]
3 //! Thread-safe reference-counting pointers.
5 //! See the [`Arc<T>`][arc] documentation for more details.
7 //! [arc]: struct.Arc.html
10 use core::sync::atomic;
11 use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};
14 use core::cmp::{self, Ordering};
15 use core::intrinsics::abort;
16 use core::mem::{self, align_of_val, size_of_val};
17 use core::ops::{Deref, Receiver, CoerceUnsized, DispatchFromDyn};
19 use core::ptr::{self, NonNull};
20 use core::marker::{Unpin, Unsize, PhantomData};
21 use core::hash::{Hash, Hasher};
22 use core::{isize, usize};
23 use core::convert::From;
24 use core::slice::from_raw_parts_mut;
26 use crate::alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
27 use crate::boxed::Box;
28 use crate::rc::is_dangling;
29 use crate::string::String;
32 /// A soft limit on the amount of references that may be made to an `Arc`.
34 /// Going above this limit will abort your program (although not
35 /// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
36 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
38 /// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically
39 /// Reference Counted'.
41 /// The type `Arc<T>` provides shared ownership of a value of type `T`,
42 /// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces
43 /// a new `Arc` instance, which points to the same value on the heap as the
44 /// source `Arc`, while increasing a reference count. When the last `Arc`
45 /// pointer to a given value is destroyed, the pointed-to value is also
48 /// Shared references in Rust disallow mutation by default, and `Arc` is no
49 /// exception: you cannot generally obtain a mutable reference to something
50 /// inside an `Arc`. If you need to mutate through an `Arc`, use
51 /// [`Mutex`][mutex], [`RwLock`][rwlock], or one of the [`Atomic`][atomic]
56 /// Unlike [`Rc<T>`], `Arc<T>` uses atomic operations for its reference
57 /// counting. This means that it is thread-safe. The disadvantage is that
58 /// atomic operations are more expensive than ordinary memory accesses. If you
59 /// are not sharing reference-counted values between threads, consider using
60 /// [`Rc<T>`] for lower overhead. [`Rc<T>`] is a safe default, because the
61 /// compiler will catch any attempt to send an [`Rc<T>`] between threads.
62 /// However, a library might choose `Arc<T>` in order to give library consumers
65 /// `Arc<T>` will implement [`Send`] and [`Sync`] as long as the `T` implements
66 /// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an
67 /// `Arc<T>` to make it thread-safe? This may be a bit counter-intuitive at
68 /// first: after all, isn't the point of `Arc<T>` thread safety? The key is
69 /// this: `Arc<T>` makes it thread safe to have multiple ownership of the same
70 /// data, but it doesn't add thread safety to its data. Consider
71 /// `Arc<`[`RefCell<T>`]`>`. [`RefCell<T>`] isn't [`Sync`], and if `Arc<T>` was always
72 /// [`Send`], `Arc<`[`RefCell<T>`]`>` would be as well. But then we'd have a problem:
73 /// [`RefCell<T>`] is not thread safe; it keeps track of the borrowing count using
74 /// non-atomic operations.
76 /// In the end, this means that you may need to pair `Arc<T>` with some sort of
77 /// [`std::sync`] type, usually [`Mutex<T>`][mutex].
79 /// ## Breaking cycles with `Weak`
81 /// The [`downgrade`][downgrade] method can be used to create a non-owning
82 /// [`Weak`][weak] pointer. A [`Weak`][weak] pointer can be [`upgrade`][upgrade]d
83 /// to an `Arc`, but this will return [`None`] if the value has already been
86 /// A cycle between `Arc` pointers will never be deallocated. For this reason,
87 /// [`Weak`][weak] is used to break cycles. For example, a tree could have
88 /// strong `Arc` pointers from parent nodes to children, and [`Weak`][weak]
89 /// pointers from children back to their parents.
91 /// # Cloning references
93 /// Creating a new reference from an existing reference counted pointer is done using the
94 /// `Clone` trait implemented for [`Arc<T>`][arc] and [`Weak<T>`][weak].
97 /// use std::sync::Arc;
98 /// let foo = Arc::new(vec![1.0, 2.0, 3.0]);
99 /// // The two syntaxes below are equivalent.
100 /// let a = foo.clone();
101 /// let b = Arc::clone(&foo);
102 /// // a, b, and foo are all Arcs that point to the same memory location
105 /// The [`Arc::clone(&from)`] syntax is the most idiomatic because it conveys more explicitly
106 /// the meaning of the code. In the example above, this syntax makes it easier to see that
107 /// this code is creating a new reference rather than copying the whole content of foo.
109 /// ## `Deref` behavior
111 /// `Arc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
112 /// so you can call `T`'s methods on a value of type `Arc<T>`. To avoid name
113 /// clashes with `T`'s methods, the methods of `Arc<T>` itself are associated
114 /// functions, called using function-like syntax:
117 /// use std::sync::Arc;
118 /// let my_arc = Arc::new(());
120 /// Arc::downgrade(&my_arc);
123 /// [`Weak<T>`][weak] does not auto-dereference to `T`, because the value may have
124 /// already been destroyed.
126 /// [arc]: struct.Arc.html
127 /// [weak]: struct.Weak.html
128 /// [`Rc<T>`]: ../../std/rc/struct.Rc.html
129 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
130 /// [mutex]: ../../std/sync/struct.Mutex.html
131 /// [rwlock]: ../../std/sync/struct.RwLock.html
132 /// [atomic]: ../../std/sync/atomic/index.html
133 /// [`Send`]: ../../std/marker/trait.Send.html
134 /// [`Sync`]: ../../std/marker/trait.Sync.html
135 /// [deref]: ../../std/ops/trait.Deref.html
136 /// [downgrade]: struct.Arc.html#method.downgrade
137 /// [upgrade]: struct.Weak.html#method.upgrade
138 /// [`None`]: ../../std/option/enum.Option.html#variant.None
139 /// [`RefCell<T>`]: ../../std/cell/struct.RefCell.html
140 /// [`std::sync`]: ../../std/sync/index.html
141 /// [`Arc::clone(&from)`]: #method.clone
145 /// Sharing some immutable data between threads:
147 // Note that we **do not** run these tests here. The windows builders get super
148 // unhappy if a thread outlives the main thread and then exits at the same time
149 // (something deadlocks) so we just avoid this entirely by not running these
152 /// use std::sync::Arc;
155 /// let five = Arc::new(5);
158 /// let five = Arc::clone(&five);
160 /// thread::spawn(move || {
161 /// println!("{:?}", five);
166 /// Sharing a mutable [`AtomicUsize`]:
168 /// [`AtomicUsize`]: ../../std/sync/atomic/struct.AtomicUsize.html
171 /// use std::sync::Arc;
172 /// use std::sync::atomic::{AtomicUsize, Ordering};
175 /// let val = Arc::new(AtomicUsize::new(5));
178 /// let val = Arc::clone(&val);
180 /// thread::spawn(move || {
181 /// let v = val.fetch_add(1, Ordering::SeqCst);
182 /// println!("{:?}", v);
187 /// See the [`rc` documentation][rc_examples] for more examples of reference
188 /// counting in general.
190 /// [rc_examples]: ../../std/rc/index.html#examples
191 #[cfg_attr(not(test), lang = "arc")]
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub struct Arc<T: ?Sized> {
194 ptr: NonNull<ArcInner<T>>,
195 phantom: PhantomData<T>,
198 #[stable(feature = "rust1", since = "1.0.0")]
199 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
200 #[stable(feature = "rust1", since = "1.0.0")]
201 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
203 #[unstable(feature = "coerce_unsized", issue = "27732")]
204 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
206 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
207 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Arc<U>> for Arc<T> {}
209 /// `Weak` is a version of [`Arc`] that holds a non-owning reference to the
210 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
211 /// pointer, which returns an [`Option`]`<`[`Arc`]`<T>>`.
213 /// Since a `Weak` reference does not count towards ownership, it will not
214 /// prevent the inner value from being dropped, and `Weak` itself makes no
215 /// guarantees about the value still being present and may return [`None`]
216 /// when [`upgrade`]d.
218 /// A `Weak` pointer is useful for keeping a temporary reference to the value
219 /// within [`Arc`] without extending its lifetime. It is also used to prevent
220 /// circular references between [`Arc`] pointers, since mutual owning references
221 /// would never allow either [`Arc`] to be dropped. For example, a tree could
222 /// have strong [`Arc`] pointers from parent nodes to children, and `Weak`
223 /// pointers from children back to their parents.
225 /// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`].
227 /// [`Arc`]: struct.Arc.html
228 /// [`Arc::downgrade`]: struct.Arc.html#method.downgrade
229 /// [`upgrade`]: struct.Weak.html#method.upgrade
230 /// [`Option`]: ../../std/option/enum.Option.html
231 /// [`None`]: ../../std/option/enum.Option.html#variant.None
232 #[stable(feature = "arc_weak", since = "1.4.0")]
233 pub struct Weak<T: ?Sized> {
234 // This is a `NonNull` to allow optimizing the size of this type in enums,
235 // but it is not necessarily a valid pointer.
236 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
237 // to allocate space on the heap. That's not a value a real pointer
238 // will ever have because RcBox has alignment at least 2.
239 ptr: NonNull<ArcInner<T>>,
242 #[stable(feature = "arc_weak", since = "1.4.0")]
243 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
244 #[stable(feature = "arc_weak", since = "1.4.0")]
245 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
247 #[unstable(feature = "coerce_unsized", issue = "27732")]
248 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
249 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
250 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
252 #[stable(feature = "arc_weak", since = "1.4.0")]
253 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 struct ArcInner<T: ?Sized> {
260 strong: atomic::AtomicUsize,
262 // the value usize::MAX acts as a sentinel for temporarily "locking" the
263 // ability to upgrade weak pointers or downgrade strong ones; this is used
264 // to avoid races in `make_mut` and `get_mut`.
265 weak: atomic::AtomicUsize,
270 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
271 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
274 /// Constructs a new `Arc<T>`.
279 /// use std::sync::Arc;
281 /// let five = Arc::new(5);
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn new(data: T) -> Arc<T> {
286 // Start the weak pointer count as 1 which is the weak pointer that's
287 // held by all the strong pointers (kinda), see std/rc.rs for more info
288 let x: Box<_> = box ArcInner {
289 strong: atomic::AtomicUsize::new(1),
290 weak: atomic::AtomicUsize::new(1),
293 Arc { ptr: Box::into_raw_non_null(x), phantom: PhantomData }
296 /// Constructs a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then
297 /// `data` will be pinned in memory and unable to be moved.
298 #[stable(feature = "pin", since = "1.33.0")]
299 pub fn pin(data: T) -> Pin<Arc<T>> {
300 unsafe { Pin::new_unchecked(Arc::new(data)) }
303 /// Returns the contained value, if the `Arc` has exactly one strong reference.
305 /// Otherwise, an [`Err`][result] is returned with the same `Arc` that was
308 /// This will succeed even if there are outstanding weak references.
310 /// [result]: ../../std/result/enum.Result.html
315 /// use std::sync::Arc;
317 /// let x = Arc::new(3);
318 /// assert_eq!(Arc::try_unwrap(x), Ok(3));
320 /// let x = Arc::new(4);
321 /// let _y = Arc::clone(&x);
322 /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
325 #[stable(feature = "arc_unique", since = "1.4.0")]
326 pub fn try_unwrap(this: Self) -> Result<T, Self> {
327 // See `drop` for why all these atomics are like this
328 if this.inner().strong.compare_exchange(1, 0, Release, Relaxed).is_err() {
332 atomic::fence(Acquire);
335 let elem = ptr::read(&this.ptr.as_ref().data);
337 // Make a weak pointer to clean up the implicit strong-weak reference
338 let _weak = Weak { ptr: this.ptr };
346 impl<T: ?Sized> Arc<T> {
347 /// Consumes the `Arc`, returning the wrapped pointer.
349 /// To avoid a memory leak the pointer must be converted back to an `Arc` using
350 /// [`Arc::from_raw`][from_raw].
352 /// [from_raw]: struct.Arc.html#method.from_raw
357 /// use std::sync::Arc;
359 /// let x = Arc::new(10);
360 /// let x_ptr = Arc::into_raw(x);
361 /// assert_eq!(unsafe { *x_ptr }, 10);
363 #[stable(feature = "rc_raw", since = "1.17.0")]
364 pub fn into_raw(this: Self) -> *const T {
365 let ptr: *const T = &*this;
370 /// Constructs an `Arc` from a raw pointer.
372 /// The raw pointer must have been previously returned by a call to a
373 /// [`Arc::into_raw`][into_raw].
375 /// This function is unsafe because improper use may lead to memory problems. For example, a
376 /// double-free may occur if the function is called twice on the same raw pointer.
378 /// [into_raw]: struct.Arc.html#method.into_raw
383 /// use std::sync::Arc;
385 /// let x = Arc::new(10);
386 /// let x_ptr = Arc::into_raw(x);
389 /// // Convert back to an `Arc` to prevent leak.
390 /// let x = Arc::from_raw(x_ptr);
391 /// assert_eq!(*x, 10);
393 /// // Further calls to `Arc::from_raw(x_ptr)` would be memory unsafe.
396 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
398 #[stable(feature = "rc_raw", since = "1.17.0")]
399 pub unsafe fn from_raw(ptr: *const T) -> Self {
400 // Align the unsized value to the end of the ArcInner.
401 // Because it is ?Sized, it will always be the last field in memory.
402 let align = align_of_val(&*ptr);
403 let layout = Layout::new::<ArcInner<()>>();
404 let offset = (layout.size() + layout.padding_needed_for(align)) as isize;
406 // Reverse the offset to find the original ArcInner.
407 let fake_ptr = ptr as *mut ArcInner<T>;
408 let arc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
411 ptr: NonNull::new_unchecked(arc_ptr),
412 phantom: PhantomData,
416 /// Consumes the `Arc`, returning the wrapped pointer as `NonNull<T>`.
421 /// #![feature(rc_into_raw_non_null)]
423 /// use std::sync::Arc;
425 /// let x = Arc::new(10);
426 /// let ptr = Arc::into_raw_non_null(x);
427 /// let deref = unsafe { *ptr.as_ref() };
428 /// assert_eq!(deref, 10);
430 #[unstable(feature = "rc_into_raw_non_null", issue = "47336")]
432 pub fn into_raw_non_null(this: Self) -> NonNull<T> {
433 // safe because Arc guarantees its pointer is non-null
434 unsafe { NonNull::new_unchecked(Arc::into_raw(this) as *mut _) }
437 /// Creates a new [`Weak`][weak] pointer to this value.
439 /// [weak]: struct.Weak.html
444 /// use std::sync::Arc;
446 /// let five = Arc::new(5);
448 /// let weak_five = Arc::downgrade(&five);
450 #[stable(feature = "arc_weak", since = "1.4.0")]
451 pub fn downgrade(this: &Self) -> Weak<T> {
452 // This Relaxed is OK because we're checking the value in the CAS
454 let mut cur = this.inner().weak.load(Relaxed);
457 // check if the weak counter is currently "locked"; if so, spin.
458 if cur == usize::MAX {
459 cur = this.inner().weak.load(Relaxed);
463 // NOTE: this code currently ignores the possibility of overflow
464 // into usize::MAX; in general both Rc and Arc need to be adjusted
465 // to deal with overflow.
467 // Unlike with Clone(), we need this to be an Acquire read to
468 // synchronize with the write coming from `is_unique`, so that the
469 // events prior to that write happen before this read.
470 match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) {
472 // Make sure we do not create a dangling Weak
473 debug_assert!(!is_dangling(this.ptr));
474 return Weak { ptr: this.ptr };
476 Err(old) => cur = old,
481 /// Gets the number of [`Weak`][weak] pointers to this value.
483 /// [weak]: struct.Weak.html
487 /// This method by itself is safe, but using it correctly requires extra care.
488 /// Another thread can change the weak count at any time,
489 /// including potentially between calling this method and acting on the result.
494 /// use std::sync::Arc;
496 /// let five = Arc::new(5);
497 /// let _weak_five = Arc::downgrade(&five);
499 /// // This assertion is deterministic because we haven't shared
500 /// // the `Arc` or `Weak` between threads.
501 /// assert_eq!(1, Arc::weak_count(&five));
504 #[stable(feature = "arc_counts", since = "1.15.0")]
505 pub fn weak_count(this: &Self) -> usize {
506 let cnt = this.inner().weak.load(SeqCst);
507 // If the weak count is currently locked, the value of the
508 // count was 0 just before taking the lock.
509 if cnt == usize::MAX { 0 } else { cnt - 1 }
512 /// Gets the number of strong (`Arc`) pointers to this value.
516 /// This method by itself is safe, but using it correctly requires extra care.
517 /// Another thread can change the strong count at any time,
518 /// including potentially between calling this method and acting on the result.
523 /// use std::sync::Arc;
525 /// let five = Arc::new(5);
526 /// let _also_five = Arc::clone(&five);
528 /// // This assertion is deterministic because we haven't shared
529 /// // the `Arc` between threads.
530 /// assert_eq!(2, Arc::strong_count(&five));
533 #[stable(feature = "arc_counts", since = "1.15.0")]
534 pub fn strong_count(this: &Self) -> usize {
535 this.inner().strong.load(SeqCst)
539 fn inner(&self) -> &ArcInner<T> {
540 // This unsafety is ok because while this arc is alive we're guaranteed
541 // that the inner pointer is valid. Furthermore, we know that the
542 // `ArcInner` structure itself is `Sync` because the inner data is
543 // `Sync` as well, so we're ok loaning out an immutable pointer to these
545 unsafe { self.ptr.as_ref() }
548 // Non-inlined part of `drop`.
550 unsafe fn drop_slow(&mut self) {
551 // Destroy the data at this time, even though we may not free the box
552 // allocation itself (there may still be weak pointers lying around).
553 ptr::drop_in_place(&mut self.ptr.as_mut().data);
555 if self.inner().weak.fetch_sub(1, Release) == 1 {
556 atomic::fence(Acquire);
557 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
562 #[stable(feature = "ptr_eq", since = "1.17.0")]
563 /// Returns `true` if the two `Arc`s point to the same value (not
564 /// just values that compare as equal).
569 /// use std::sync::Arc;
571 /// let five = Arc::new(5);
572 /// let same_five = Arc::clone(&five);
573 /// let other_five = Arc::new(5);
575 /// assert!(Arc::ptr_eq(&five, &same_five));
576 /// assert!(!Arc::ptr_eq(&five, &other_five));
578 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
579 this.ptr.as_ptr() == other.ptr.as_ptr()
583 impl<T: ?Sized> Arc<T> {
584 // Allocates an `ArcInner<T>` with sufficient space for an unsized value
585 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
586 // Calculate layout using the given value.
587 // Previously, layout was calculated on the expression
588 // `&*(ptr as *const ArcInner<T>)`, but this created a misaligned
589 // reference (see #54908).
590 let layout = Layout::new::<ArcInner<()>>()
591 .extend(Layout::for_value(&*ptr)).unwrap().0
592 .pad_to_align().unwrap();
594 let mem = Global.alloc(layout)
595 .unwrap_or_else(|_| handle_alloc_error(layout));
597 // Initialize the ArcInner
598 let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut ArcInner<T>;
599 debug_assert_eq!(Layout::for_value(&*inner), layout);
601 ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1));
602 ptr::write(&mut (*inner).weak, atomic::AtomicUsize::new(1));
607 fn from_box(v: Box<T>) -> Arc<T> {
609 let box_unique = Box::into_unique(v);
610 let bptr = box_unique.as_ptr();
612 let value_size = size_of_val(&*bptr);
613 let ptr = Self::allocate_for_ptr(bptr);
615 // Copy value as bytes
616 ptr::copy_nonoverlapping(
617 bptr as *const T as *const u8,
618 &mut (*ptr).data as *mut _ as *mut u8,
621 // Free the allocation without dropping its contents
622 box_free(box_unique);
624 Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
629 // Sets the data pointer of a `?Sized` raw pointer.
631 // For a slice/trait object, this sets the `data` field and leaves the rest
632 // unchanged. For a sized raw pointer, this simply sets the pointer.
633 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
634 ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
639 // Copy elements from slice into newly allocated Arc<[T]>
641 // Unsafe because the caller must either take ownership or bind `T: Copy`
642 unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> {
643 let v_ptr = v as *const [T];
644 let ptr = Self::allocate_for_ptr(v_ptr);
646 ptr::copy_nonoverlapping(
648 &mut (*ptr).data as *mut [T] as *mut T,
651 Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
655 // Specialization trait used for From<&[T]>
656 trait ArcFromSlice<T> {
657 fn from_slice(slice: &[T]) -> Self;
660 impl<T: Clone> ArcFromSlice<T> for Arc<[T]> {
662 default fn from_slice(v: &[T]) -> Self {
663 // Panic guard while cloning T elements.
664 // In the event of a panic, elements that have been written
665 // into the new ArcInner will be dropped, then the memory freed.
673 impl<T> Drop for Guard<T> {
676 let slice = from_raw_parts_mut(self.elems, self.n_elems);
677 ptr::drop_in_place(slice);
679 Global.dealloc(self.mem.cast(), self.layout.clone());
685 let v_ptr = v as *const [T];
686 let ptr = Self::allocate_for_ptr(v_ptr);
688 let mem = ptr as *mut _ as *mut u8;
689 let layout = Layout::for_value(&*ptr);
691 // Pointer to first element
692 let elems = &mut (*ptr).data as *mut [T] as *mut T;
694 let mut guard = Guard{
695 mem: NonNull::new_unchecked(mem),
701 for (i, item) in v.iter().enumerate() {
702 ptr::write(elems.add(i), item.clone());
706 // All clear. Forget the guard so it doesn't free the new ArcInner.
709 Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
714 impl<T: Copy> ArcFromSlice<T> for Arc<[T]> {
716 fn from_slice(v: &[T]) -> Self {
717 unsafe { Arc::copy_from_slice(v) }
721 #[stable(feature = "rust1", since = "1.0.0")]
722 impl<T: ?Sized> Clone for Arc<T> {
723 /// Makes a clone of the `Arc` pointer.
725 /// This creates another pointer to the same inner value, increasing the
726 /// strong reference count.
731 /// use std::sync::Arc;
733 /// let five = Arc::new(5);
735 /// let _ = Arc::clone(&five);
738 fn clone(&self) -> Arc<T> {
739 // Using a relaxed ordering is alright here, as knowledge of the
740 // original reference prevents other threads from erroneously deleting
743 // As explained in the [Boost documentation][1], Increasing the
744 // reference counter can always be done with memory_order_relaxed: New
745 // references to an object can only be formed from an existing
746 // reference, and passing an existing reference from one thread to
747 // another must already provide any required synchronization.
749 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
750 let old_size = self.inner().strong.fetch_add(1, Relaxed);
752 // However we need to guard against massive refcounts in case someone
753 // is `mem::forget`ing Arcs. If we don't do this the count can overflow
754 // and users will use-after free. We racily saturate to `isize::MAX` on
755 // the assumption that there aren't ~2 billion threads incrementing
756 // the reference count at once. This branch will never be taken in
757 // any realistic program.
759 // We abort because such a program is incredibly degenerate, and we
760 // don't care to support it.
761 if old_size > MAX_REFCOUNT {
767 Arc { ptr: self.ptr, phantom: PhantomData }
771 #[stable(feature = "rust1", since = "1.0.0")]
772 impl<T: ?Sized> Deref for Arc<T> {
776 fn deref(&self) -> &T {
781 #[unstable(feature = "receiver_trait", issue = "0")]
782 impl<T: ?Sized> Receiver for Arc<T> {}
784 impl<T: Clone> Arc<T> {
785 /// Makes a mutable reference into the given `Arc`.
787 /// If there are other `Arc` or [`Weak`][weak] pointers to the same value,
788 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
789 /// ensure unique ownership. This is also referred to as clone-on-write.
791 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
793 /// [weak]: struct.Weak.html
794 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
795 /// [get_mut]: struct.Arc.html#method.get_mut
800 /// use std::sync::Arc;
802 /// let mut data = Arc::new(5);
804 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
805 /// let mut other_data = Arc::clone(&data); // Won't clone inner data
806 /// *Arc::make_mut(&mut data) += 1; // Clones inner data
807 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
808 /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything
810 /// // Now `data` and `other_data` point to different values.
811 /// assert_eq!(*data, 8);
812 /// assert_eq!(*other_data, 12);
815 #[stable(feature = "arc_unique", since = "1.4.0")]
816 pub fn make_mut(this: &mut Self) -> &mut T {
817 // Note that we hold both a strong reference and a weak reference.
818 // Thus, releasing our strong reference only will not, by itself, cause
819 // the memory to be deallocated.
821 // Use Acquire to ensure that we see any writes to `weak` that happen
822 // before release writes (i.e., decrements) to `strong`. Since we hold a
823 // weak count, there's no chance the ArcInner itself could be
825 if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() {
826 // Another strong pointer exists; clone
827 *this = Arc::new((**this).clone());
828 } else if this.inner().weak.load(Relaxed) != 1 {
829 // Relaxed suffices in the above because this is fundamentally an
830 // optimization: we are always racing with weak pointers being
831 // dropped. Worst case, we end up allocated a new Arc unnecessarily.
833 // We removed the last strong ref, but there are additional weak
834 // refs remaining. We'll move the contents to a new Arc, and
835 // invalidate the other weak refs.
837 // Note that it is not possible for the read of `weak` to yield
838 // usize::MAX (i.e., locked), since the weak count can only be
839 // locked by a thread with a strong reference.
841 // Materialize our own implicit weak pointer, so that it can clean
842 // up the ArcInner as needed.
843 let weak = Weak { ptr: this.ptr };
845 // mark the data itself as already deallocated
847 // there is no data race in the implicit write caused by `read`
848 // here (due to zeroing) because data is no longer accessed by
849 // other threads (due to there being no more strong refs at this
851 let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data));
852 mem::swap(this, &mut swap);
856 // We were the sole reference of either kind; bump back up the
858 this.inner().strong.store(1, Release);
861 // As with `get_mut()`, the unsafety is ok because our reference was
862 // either unique to begin with, or became one upon cloning the contents.
864 &mut this.ptr.as_mut().data
869 impl<T: ?Sized> Arc<T> {
870 /// Returns a mutable reference to the inner value, if there are
871 /// no other `Arc` or [`Weak`][weak] pointers to the same value.
873 /// Returns [`None`][option] otherwise, because it is not safe to
874 /// mutate a shared value.
876 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
877 /// the inner value when it's shared.
879 /// [weak]: struct.Weak.html
880 /// [option]: ../../std/option/enum.Option.html
881 /// [make_mut]: struct.Arc.html#method.make_mut
882 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
887 /// use std::sync::Arc;
889 /// let mut x = Arc::new(3);
890 /// *Arc::get_mut(&mut x).unwrap() = 4;
891 /// assert_eq!(*x, 4);
893 /// let _y = Arc::clone(&x);
894 /// assert!(Arc::get_mut(&mut x).is_none());
897 #[stable(feature = "arc_unique", since = "1.4.0")]
898 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
899 if this.is_unique() {
900 // This unsafety is ok because we're guaranteed that the pointer
901 // returned is the *only* pointer that will ever be returned to T. Our
902 // reference count is guaranteed to be 1 at this point, and we required
903 // the Arc itself to be `mut`, so we're returning the only possible
904 // reference to the inner data.
906 Some(&mut this.ptr.as_mut().data)
913 /// Determine whether this is the unique reference (including weak refs) to
914 /// the underlying data.
916 /// Note that this requires locking the weak ref count.
917 fn is_unique(&mut self) -> bool {
918 // lock the weak pointer count if we appear to be the sole weak pointer
921 // The acquire label here ensures a happens-before relationship with any
922 // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements
923 // of the `weak` count (via `Weak::drop`, which uses release). If the upgraded
924 // weak ref was never dropped, the CAS here will fail so we do not care to synchronize.
925 if self.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() {
926 // This needs to be an `Acquire` to synchronize with the decrement of the `strong`
927 // counter in `drop` -- the only access that happens when any but the last reference
929 let unique = self.inner().strong.load(Acquire) == 1;
931 // The release write here synchronizes with a read in `downgrade`,
932 // effectively preventing the above read of `strong` from happening
934 self.inner().weak.store(1, Release); // release the lock
942 #[stable(feature = "rust1", since = "1.0.0")]
943 unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
946 /// This will decrement the strong reference count. If the strong reference
947 /// count reaches zero then the only other references (if any) are
948 /// [`Weak`], so we `drop` the inner value.
953 /// use std::sync::Arc;
957 /// impl Drop for Foo {
958 /// fn drop(&mut self) {
959 /// println!("dropped!");
963 /// let foo = Arc::new(Foo);
964 /// let foo2 = Arc::clone(&foo);
966 /// drop(foo); // Doesn't print anything
967 /// drop(foo2); // Prints "dropped!"
970 /// [`Weak`]: ../../std/sync/struct.Weak.html
973 // Because `fetch_sub` is already atomic, we do not need to synchronize
974 // with other threads unless we are going to delete the object. This
975 // same logic applies to the below `fetch_sub` to the `weak` count.
976 if self.inner().strong.fetch_sub(1, Release) != 1 {
980 // This fence is needed to prevent reordering of use of the data and
981 // deletion of the data. Because it is marked `Release`, the decreasing
982 // of the reference count synchronizes with this `Acquire` fence. This
983 // means that use of the data happens before decreasing the reference
984 // count, which happens before this fence, which happens before the
985 // deletion of the data.
987 // As explained in the [Boost documentation][1],
989 // > It is important to enforce any possible access to the object in one
990 // > thread (through an existing reference) to *happen before* deleting
991 // > the object in a different thread. This is achieved by a "release"
992 // > operation after dropping a reference (any access to the object
993 // > through this reference must obviously happened before), and an
994 // > "acquire" operation before deleting the object.
996 // In particular, while the contents of an Arc are usually immutable, it's
997 // possible to have interior writes to something like a Mutex<T>. Since a
998 // Mutex is not acquired when it is deleted, we can't rely on its
999 // synchronization logic to make writes in thread A visible to a destructor
1000 // running in thread B.
1002 // Also note that the Acquire fence here could probably be replaced with an
1003 // Acquire load, which could improve performance in highly-contended
1004 // situations. See [2].
1006 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
1007 // [2]: (https://github.com/rust-lang/rust/pull/41714)
1008 atomic::fence(Acquire);
1016 impl Arc<dyn Any + Send + Sync> {
1018 #[stable(feature = "rc_downcast", since = "1.29.0")]
1019 /// Attempt to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.
1024 /// use std::any::Any;
1025 /// use std::sync::Arc;
1027 /// fn print_if_string(value: Arc<dyn Any + Send + Sync>) {
1028 /// if let Ok(string) = value.downcast::<String>() {
1029 /// println!("String ({}): {}", string.len(), string);
1034 /// let my_string = "Hello World".to_string();
1035 /// print_if_string(Arc::new(my_string));
1036 /// print_if_string(Arc::new(0i8));
1039 pub fn downcast<T>(self) -> Result<Arc<T>, Self>
1041 T: Any + Send + Sync + 'static,
1043 if (*self).is::<T>() {
1044 let ptr = self.ptr.cast::<ArcInner<T>>();
1046 Ok(Arc { ptr, phantom: PhantomData })
1054 /// Constructs a new `Weak<T>`, without allocating any memory.
1055 /// Calling [`upgrade`] on the return value always gives [`None`].
1057 /// [`upgrade`]: struct.Weak.html#method.upgrade
1058 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1063 /// use std::sync::Weak;
1065 /// let empty: Weak<i64> = Weak::new();
1066 /// assert!(empty.upgrade().is_none());
1068 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1069 pub fn new() -> Weak<T> {
1071 ptr: NonNull::new(usize::MAX as *mut ArcInner<T>).expect("MAX is not 0"),
1076 impl<T: ?Sized> Weak<T> {
1077 /// Attempts to upgrade the `Weak` pointer to an [`Arc`], extending
1078 /// the lifetime of the value if successful.
1080 /// Returns [`None`] if the value has since been dropped.
1082 /// [`Arc`]: struct.Arc.html
1083 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1088 /// use std::sync::Arc;
1090 /// let five = Arc::new(5);
1092 /// let weak_five = Arc::downgrade(&five);
1094 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
1095 /// assert!(strong_five.is_some());
1097 /// // Destroy all strong pointers.
1098 /// drop(strong_five);
1101 /// assert!(weak_five.upgrade().is_none());
1103 #[stable(feature = "arc_weak", since = "1.4.0")]
1104 pub fn upgrade(&self) -> Option<Arc<T>> {
1105 // We use a CAS loop to increment the strong count instead of a
1106 // fetch_add because once the count hits 0 it must never be above 0.
1107 let inner = self.inner()?;
1109 // Relaxed load because any write of 0 that we can observe
1110 // leaves the field in a permanently zero state (so a
1111 // "stale" read of 0 is fine), and any other value is
1112 // confirmed via the CAS below.
1113 let mut n = inner.strong.load(Relaxed);
1120 // See comments in `Arc::clone` for why we do this (for `mem::forget`).
1121 if n > MAX_REFCOUNT {
1127 // Relaxed is valid for the same reason it is on Arc's Clone impl
1128 match inner.strong.compare_exchange_weak(n, n + 1, Relaxed, Relaxed) {
1129 Ok(_) => return Some(Arc {
1130 // null checked above
1132 phantom: PhantomData,
1134 Err(old) => n = old,
1139 /// Gets the number of strong (`Arc`) pointers pointing to this value.
1141 /// If `self` was created using [`Weak::new`], this will return 0.
1143 /// [`Weak::new`]: #method.new
1144 #[unstable(feature = "weak_counts", issue = "57977")]
1145 pub fn strong_count(&self) -> usize {
1146 if let Some(inner) = self.inner() {
1147 inner.strong.load(SeqCst)
1153 /// Gets an approximation of the number of `Weak` pointers pointing to this
1156 /// If `self` was created using [`Weak::new`], this will return 0. If not,
1157 /// the returned value is at least 1, since `self` still points to the
1162 /// Due to implementation details, the returned value can be off by 1 in
1163 /// either direction when other threads are manipulating any `Arc`s or
1164 /// `Weak`s pointing to the same value.
1166 /// [`Weak::new`]: #method.new
1167 #[unstable(feature = "weak_counts", issue = "57977")]
1168 pub fn weak_count(&self) -> Option<usize> {
1169 // Due to the implicit weak pointer added when any strong pointers are
1170 // around, we cannot implement `weak_count` correctly since it
1171 // necessarily requires accessing the strong count and weak count in an
1172 // unsynchronized fashion. So this version is a bit racy.
1173 self.inner().map(|inner| {
1174 let strong = inner.strong.load(SeqCst);
1175 let weak = inner.weak.load(SeqCst);
1177 // If the last `Arc` has *just* been dropped, it might not yet
1178 // have removed the implicit weak count, so the value we get
1179 // here might be 1 too high.
1182 // As long as there's still at least 1 `Arc` around, subtract
1183 // the implicit weak pointer.
1184 // Note that the last `Arc` might get dropped between the 2
1185 // loads we do above, removing the implicit weak pointer. This
1186 // means that the value might be 1 too low here. In order to not
1187 // return 0 here (which would happen if we're the only weak
1188 // pointer), we guard against that specifically.
1189 cmp::max(1, weak - 1)
1194 /// Returns `None` when the pointer is dangling and there is no allocated `ArcInner`,
1195 /// (i.e., when this `Weak` was created by `Weak::new`).
1197 fn inner(&self) -> Option<&ArcInner<T>> {
1198 if is_dangling(self.ptr) {
1201 Some(unsafe { self.ptr.as_ref() })
1205 /// Returns `true` if the two `Weak`s point to the same value (not just values
1206 /// that compare as equal).
1210 /// Since this compares pointers it means that `Weak::new()` will equal each
1211 /// other, even though they don't point to any value.
1217 /// #![feature(weak_ptr_eq)]
1218 /// use std::sync::{Arc, Weak};
1220 /// let first_rc = Arc::new(5);
1221 /// let first = Arc::downgrade(&first_rc);
1222 /// let second = Arc::downgrade(&first_rc);
1224 /// assert!(Weak::ptr_eq(&first, &second));
1226 /// let third_rc = Arc::new(5);
1227 /// let third = Arc::downgrade(&third_rc);
1229 /// assert!(!Weak::ptr_eq(&first, &third));
1232 /// Comparing `Weak::new`.
1235 /// #![feature(weak_ptr_eq)]
1236 /// use std::sync::{Arc, Weak};
1238 /// let first = Weak::new();
1239 /// let second = Weak::new();
1240 /// assert!(Weak::ptr_eq(&first, &second));
1242 /// let third_rc = Arc::new(());
1243 /// let third = Arc::downgrade(&third_rc);
1244 /// assert!(!Weak::ptr_eq(&first, &third));
1247 #[unstable(feature = "weak_ptr_eq", issue = "55981")]
1248 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1249 this.ptr.as_ptr() == other.ptr.as_ptr()
1253 #[stable(feature = "arc_weak", since = "1.4.0")]
1254 impl<T: ?Sized> Clone for Weak<T> {
1255 /// Makes a clone of the `Weak` pointer that points to the same value.
1260 /// use std::sync::{Arc, Weak};
1262 /// let weak_five = Arc::downgrade(&Arc::new(5));
1264 /// let _ = Weak::clone(&weak_five);
1267 fn clone(&self) -> Weak<T> {
1268 let inner = if let Some(inner) = self.inner() {
1271 return Weak { ptr: self.ptr };
1273 // See comments in Arc::clone() for why this is relaxed. This can use a
1274 // fetch_add (ignoring the lock) because the weak count is only locked
1275 // where are *no other* weak pointers in existence. (So we can't be
1276 // running this code in that case).
1277 let old_size = inner.weak.fetch_add(1, Relaxed);
1279 // See comments in Arc::clone() for why we do this (for mem::forget).
1280 if old_size > MAX_REFCOUNT {
1286 return Weak { ptr: self.ptr };
1290 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1291 impl<T> Default for Weak<T> {
1292 /// Constructs a new `Weak<T>`, without allocating memory.
1293 /// Calling [`upgrade`] on the return value always
1296 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1297 /// [`upgrade`]: ../../std/sync/struct.Weak.html#method.upgrade
1302 /// use std::sync::Weak;
1304 /// let empty: Weak<i64> = Default::default();
1305 /// assert!(empty.upgrade().is_none());
1307 fn default() -> Weak<T> {
1312 #[stable(feature = "arc_weak", since = "1.4.0")]
1313 impl<T: ?Sized> Drop for Weak<T> {
1314 /// Drops the `Weak` pointer.
1319 /// use std::sync::{Arc, Weak};
1323 /// impl Drop for Foo {
1324 /// fn drop(&mut self) {
1325 /// println!("dropped!");
1329 /// let foo = Arc::new(Foo);
1330 /// let weak_foo = Arc::downgrade(&foo);
1331 /// let other_weak_foo = Weak::clone(&weak_foo);
1333 /// drop(weak_foo); // Doesn't print anything
1334 /// drop(foo); // Prints "dropped!"
1336 /// assert!(other_weak_foo.upgrade().is_none());
1338 fn drop(&mut self) {
1339 // If we find out that we were the last weak pointer, then its time to
1340 // deallocate the data entirely. See the discussion in Arc::drop() about
1341 // the memory orderings
1343 // It's not necessary to check for the locked state here, because the
1344 // weak count can only be locked if there was precisely one weak ref,
1345 // meaning that drop could only subsequently run ON that remaining weak
1346 // ref, which can only happen after the lock is released.
1347 let inner = if let Some(inner) = self.inner() {
1353 if inner.weak.fetch_sub(1, Release) == 1 {
1354 atomic::fence(Acquire);
1356 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
1362 #[stable(feature = "rust1", since = "1.0.0")]
1363 trait ArcEqIdent<T: ?Sized + PartialEq> {
1364 fn eq(&self, other: &Arc<T>) -> bool;
1365 fn ne(&self, other: &Arc<T>) -> bool;
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 impl<T: ?Sized + PartialEq> ArcEqIdent<T> for Arc<T> {
1371 default fn eq(&self, other: &Arc<T>) -> bool {
1375 default fn ne(&self, other: &Arc<T>) -> bool {
1380 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1381 /// would otherwise add a cost to all equality checks on refs. We assume that `Arc`s are used to
1382 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1383 /// cost to pay off more easily. It's also more likely to have two `Arc` clones, that point to
1384 /// the same value, than two `&T`s.
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 impl<T: ?Sized + Eq> ArcEqIdent<T> for Arc<T> {
1388 fn eq(&self, other: &Arc<T>) -> bool {
1389 Arc::ptr_eq(self, other) || **self == **other
1393 fn ne(&self, other: &Arc<T>) -> bool {
1394 !Arc::ptr_eq(self, other) && **self != **other
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
1400 /// Equality for two `Arc`s.
1402 /// Two `Arc`s are equal if their inner values are equal.
1404 /// If `T` also implements `Eq`, two `Arc`s that point to the same value are
1410 /// use std::sync::Arc;
1412 /// let five = Arc::new(5);
1414 /// assert!(five == Arc::new(5));
1417 fn eq(&self, other: &Arc<T>) -> bool {
1418 ArcEqIdent::eq(self, other)
1421 /// Inequality for two `Arc`s.
1423 /// Two `Arc`s are unequal if their inner values are unequal.
1425 /// If `T` also implements `Eq`, two `Arc`s that point to the same value are
1431 /// use std::sync::Arc;
1433 /// let five = Arc::new(5);
1435 /// assert!(five != Arc::new(6));
1438 fn ne(&self, other: &Arc<T>) -> bool {
1439 ArcEqIdent::ne(self, other)
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
1445 /// Partial comparison for two `Arc`s.
1447 /// The two are compared by calling `partial_cmp()` on their inner values.
1452 /// use std::sync::Arc;
1453 /// use std::cmp::Ordering;
1455 /// let five = Arc::new(5);
1457 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
1459 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
1460 (**self).partial_cmp(&**other)
1463 /// Less-than comparison for two `Arc`s.
1465 /// The two are compared by calling `<` on their inner values.
1470 /// use std::sync::Arc;
1472 /// let five = Arc::new(5);
1474 /// assert!(five < Arc::new(6));
1476 fn lt(&self, other: &Arc<T>) -> bool {
1477 *(*self) < *(*other)
1480 /// 'Less than or equal to' comparison for two `Arc`s.
1482 /// The two are compared by calling `<=` on their inner values.
1487 /// use std::sync::Arc;
1489 /// let five = Arc::new(5);
1491 /// assert!(five <= Arc::new(5));
1493 fn le(&self, other: &Arc<T>) -> bool {
1494 *(*self) <= *(*other)
1497 /// Greater-than comparison for two `Arc`s.
1499 /// The two are compared by calling `>` on their inner values.
1504 /// use std::sync::Arc;
1506 /// let five = Arc::new(5);
1508 /// assert!(five > Arc::new(4));
1510 fn gt(&self, other: &Arc<T>) -> bool {
1511 *(*self) > *(*other)
1514 /// 'Greater than or equal to' comparison for two `Arc`s.
1516 /// The two are compared by calling `>=` on their inner values.
1521 /// use std::sync::Arc;
1523 /// let five = Arc::new(5);
1525 /// assert!(five >= Arc::new(5));
1527 fn ge(&self, other: &Arc<T>) -> bool {
1528 *(*self) >= *(*other)
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 impl<T: ?Sized + Ord> Ord for Arc<T> {
1533 /// Comparison for two `Arc`s.
1535 /// The two are compared by calling `cmp()` on their inner values.
1540 /// use std::sync::Arc;
1541 /// use std::cmp::Ordering;
1543 /// let five = Arc::new(5);
1545 /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
1547 fn cmp(&self, other: &Arc<T>) -> Ordering {
1548 (**self).cmp(&**other)
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 impl<T: ?Sized + Eq> Eq for Arc<T> {}
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
1556 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1557 fmt::Display::fmt(&**self, f)
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
1563 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1564 fmt::Debug::fmt(&**self, f)
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl<T: ?Sized> fmt::Pointer for Arc<T> {
1570 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1571 fmt::Pointer::fmt(&(&**self as *const T), f)
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<T: Default> Default for Arc<T> {
1577 /// Creates a new `Arc<T>`, with the `Default` value for `T`.
1582 /// use std::sync::Arc;
1584 /// let x: Arc<i32> = Default::default();
1585 /// assert_eq!(*x, 0);
1587 fn default() -> Arc<T> {
1588 Arc::new(Default::default())
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<T: ?Sized + Hash> Hash for Arc<T> {
1594 fn hash<H: Hasher>(&self, state: &mut H) {
1595 (**self).hash(state)
1599 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1600 impl<T> From<T> for Arc<T> {
1601 fn from(t: T) -> Self {
1606 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1607 impl<T: Clone> From<&[T]> for Arc<[T]> {
1609 fn from(v: &[T]) -> Arc<[T]> {
1610 <Self as ArcFromSlice<T>>::from_slice(v)
1614 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1615 impl From<&str> for Arc<str> {
1617 fn from(v: &str) -> Arc<str> {
1618 let arc = Arc::<[u8]>::from(v.as_bytes());
1619 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) }
1623 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1624 impl From<String> for Arc<str> {
1626 fn from(v: String) -> Arc<str> {
1631 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1632 impl<T: ?Sized> From<Box<T>> for Arc<T> {
1634 fn from(v: Box<T>) -> Arc<T> {
1639 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1640 impl<T> From<Vec<T>> for Arc<[T]> {
1642 fn from(mut v: Vec<T>) -> Arc<[T]> {
1644 let arc = Arc::copy_from_slice(&v);
1646 // Allow the Vec to free its memory, but not destroy its contents
1656 use std::boxed::Box;
1657 use std::clone::Clone;
1658 use std::sync::mpsc::channel;
1661 use std::option::Option::{self, None, Some};
1662 use std::sync::atomic::{self, Ordering::{Acquire, SeqCst}};
1664 use std::sync::Mutex;
1665 use std::convert::From;
1667 use super::{Arc, Weak};
1668 use crate::vec::Vec;
1670 struct Canary(*mut atomic::AtomicUsize);
1672 impl Drop for Canary {
1673 fn drop(&mut self) {
1677 (*c).fetch_add(1, SeqCst);
1685 #[cfg_attr(target_os = "emscripten", ignore)]
1686 #[cfg(not(miri))] // Miri does not support threads
1687 fn manually_share_arc() {
1688 let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1689 let arc_v = Arc::new(v);
1691 let (tx, rx) = channel();
1693 let _t = thread::spawn(move || {
1694 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
1695 assert_eq!((*arc_v)[3], 4);
1698 tx.send(arc_v.clone()).unwrap();
1700 assert_eq!((*arc_v)[2], 3);
1701 assert_eq!((*arc_v)[4], 5);
1705 fn test_arc_get_mut() {
1706 let mut x = Arc::new(3);
1707 *Arc::get_mut(&mut x).unwrap() = 4;
1710 assert!(Arc::get_mut(&mut x).is_none());
1712 assert!(Arc::get_mut(&mut x).is_some());
1713 let _w = Arc::downgrade(&x);
1714 assert!(Arc::get_mut(&mut x).is_none());
1719 assert_eq!(Weak::weak_count(&Weak::<u64>::new()), None);
1720 assert_eq!(Weak::strong_count(&Weak::<u64>::new()), 0);
1722 let a = Arc::new(0);
1723 let w = Arc::downgrade(&a);
1724 assert_eq!(Weak::strong_count(&w), 1);
1725 assert_eq!(Weak::weak_count(&w), Some(1));
1727 assert_eq!(Weak::strong_count(&w), 1);
1728 assert_eq!(Weak::weak_count(&w), Some(2));
1729 assert_eq!(Weak::strong_count(&w2), 1);
1730 assert_eq!(Weak::weak_count(&w2), Some(2));
1732 assert_eq!(Weak::strong_count(&w2), 1);
1733 assert_eq!(Weak::weak_count(&w2), Some(1));
1735 assert_eq!(Weak::strong_count(&w2), 2);
1736 assert_eq!(Weak::weak_count(&w2), Some(1));
1739 assert_eq!(Weak::strong_count(&w2), 0);
1740 assert_eq!(Weak::weak_count(&w2), Some(1));
1746 let x = Arc::new(3);
1747 assert_eq!(Arc::try_unwrap(x), Ok(3));
1748 let x = Arc::new(4);
1750 assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
1751 let x = Arc::new(5);
1752 let _w = Arc::downgrade(&x);
1753 assert_eq!(Arc::try_unwrap(x), Ok(5));
1757 fn into_from_raw() {
1758 let x = Arc::new(box "hello");
1761 let x_ptr = Arc::into_raw(x);
1764 assert_eq!(**x_ptr, "hello");
1766 let x = Arc::from_raw(x_ptr);
1767 assert_eq!(**x, "hello");
1769 assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
1774 fn test_into_from_raw_unsized() {
1775 use std::fmt::Display;
1776 use std::string::ToString;
1778 let arc: Arc<str> = Arc::from("foo");
1780 let ptr = Arc::into_raw(arc.clone());
1781 let arc2 = unsafe { Arc::from_raw(ptr) };
1783 assert_eq!(unsafe { &*ptr }, "foo");
1784 assert_eq!(arc, arc2);
1786 let arc: Arc<dyn Display> = Arc::new(123);
1788 let ptr = Arc::into_raw(arc.clone());
1789 let arc2 = unsafe { Arc::from_raw(ptr) };
1791 assert_eq!(unsafe { &*ptr }.to_string(), "123");
1792 assert_eq!(arc2.to_string(), "123");
1796 fn test_cowarc_clone_make_mut() {
1797 let mut cow0 = Arc::new(75);
1798 let mut cow1 = cow0.clone();
1799 let mut cow2 = cow1.clone();
1801 assert!(75 == *Arc::make_mut(&mut cow0));
1802 assert!(75 == *Arc::make_mut(&mut cow1));
1803 assert!(75 == *Arc::make_mut(&mut cow2));
1805 *Arc::make_mut(&mut cow0) += 1;
1806 *Arc::make_mut(&mut cow1) += 2;
1807 *Arc::make_mut(&mut cow2) += 3;
1809 assert!(76 == *cow0);
1810 assert!(77 == *cow1);
1811 assert!(78 == *cow2);
1813 // none should point to the same backing memory
1814 assert!(*cow0 != *cow1);
1815 assert!(*cow0 != *cow2);
1816 assert!(*cow1 != *cow2);
1820 fn test_cowarc_clone_unique2() {
1821 let mut cow0 = Arc::new(75);
1822 let cow1 = cow0.clone();
1823 let cow2 = cow1.clone();
1825 assert!(75 == *cow0);
1826 assert!(75 == *cow1);
1827 assert!(75 == *cow2);
1829 *Arc::make_mut(&mut cow0) += 1;
1830 assert!(76 == *cow0);
1831 assert!(75 == *cow1);
1832 assert!(75 == *cow2);
1834 // cow1 and cow2 should share the same contents
1835 // cow0 should have a unique reference
1836 assert!(*cow0 != *cow1);
1837 assert!(*cow0 != *cow2);
1838 assert!(*cow1 == *cow2);
1842 fn test_cowarc_clone_weak() {
1843 let mut cow0 = Arc::new(75);
1844 let cow1_weak = Arc::downgrade(&cow0);
1846 assert!(75 == *cow0);
1847 assert!(75 == *cow1_weak.upgrade().unwrap());
1849 *Arc::make_mut(&mut cow0) += 1;
1851 assert!(76 == *cow0);
1852 assert!(cow1_weak.upgrade().is_none());
1857 let x = Arc::new(5);
1858 let y = Arc::downgrade(&x);
1859 assert!(y.upgrade().is_some());
1864 let x = Arc::new(5);
1865 let y = Arc::downgrade(&x);
1867 assert!(y.upgrade().is_none());
1871 fn weak_self_cyclic() {
1873 x: Mutex<Option<Weak<Cycle>>>,
1876 let a = Arc::new(Cycle { x: Mutex::new(None) });
1877 let b = Arc::downgrade(&a.clone());
1878 *a.x.lock().unwrap() = Some(b);
1880 // hopefully we don't double-free (or leak)...
1885 let mut canary = atomic::AtomicUsize::new(0);
1886 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1888 assert!(canary.load(Acquire) == 1);
1892 fn drop_arc_weak() {
1893 let mut canary = atomic::AtomicUsize::new(0);
1894 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1895 let arc_weak = Arc::downgrade(&arc);
1896 assert!(canary.load(Acquire) == 0);
1898 assert!(canary.load(Acquire) == 1);
1903 fn test_strong_count() {
1904 let a = Arc::new(0);
1905 assert!(Arc::strong_count(&a) == 1);
1906 let w = Arc::downgrade(&a);
1907 assert!(Arc::strong_count(&a) == 1);
1908 let b = w.upgrade().expect("");
1909 assert!(Arc::strong_count(&b) == 2);
1910 assert!(Arc::strong_count(&a) == 2);
1913 assert!(Arc::strong_count(&b) == 1);
1915 assert!(Arc::strong_count(&b) == 2);
1916 assert!(Arc::strong_count(&c) == 2);
1920 fn test_weak_count() {
1921 let a = Arc::new(0);
1922 assert!(Arc::strong_count(&a) == 1);
1923 assert!(Arc::weak_count(&a) == 0);
1924 let w = Arc::downgrade(&a);
1925 assert!(Arc::strong_count(&a) == 1);
1926 assert!(Arc::weak_count(&a) == 1);
1928 assert!(Arc::weak_count(&a) == 2);
1931 assert!(Arc::strong_count(&a) == 1);
1932 assert!(Arc::weak_count(&a) == 0);
1934 assert!(Arc::strong_count(&a) == 2);
1935 assert!(Arc::weak_count(&a) == 0);
1936 let d = Arc::downgrade(&c);
1937 assert!(Arc::weak_count(&c) == 1);
1938 assert!(Arc::strong_count(&c) == 2);
1947 let a = Arc::new(5);
1948 assert_eq!(format!("{:?}", a), "5");
1951 // Make sure deriving works with Arc<T>
1952 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1959 let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1960 assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1961 let y = Arc::downgrade(&x.clone());
1963 assert!(y.upgrade().is_none());
1967 fn test_from_owned() {
1969 let foo_arc = Arc::from(foo);
1970 assert!(123 == *foo_arc);
1974 fn test_new_weak() {
1975 let foo: Weak<usize> = Weak::new();
1976 assert!(foo.upgrade().is_none());
1981 let five = Arc::new(5);
1982 let same_five = five.clone();
1983 let other_five = Arc::new(5);
1985 assert!(Arc::ptr_eq(&five, &same_five));
1986 assert!(!Arc::ptr_eq(&five, &other_five));
1990 #[cfg_attr(target_os = "emscripten", ignore)]
1991 #[cfg(not(miri))] // Miri does not support threads
1992 fn test_weak_count_locked() {
1993 let mut a = Arc::new(atomic::AtomicBool::new(false));
1995 let t = thread::spawn(move || {
1996 for _i in 0..1000000 {
1997 Arc::get_mut(&mut a);
1999 a.store(true, SeqCst);
2002 while !a2.load(SeqCst) {
2003 let n = Arc::weak_count(&a2);
2004 assert!(n < 2, "bad weak count: {}", n);
2010 fn test_from_str() {
2011 let r: Arc<str> = Arc::from("foo");
2013 assert_eq!(&r[..], "foo");
2017 fn test_copy_from_slice() {
2018 let s: &[u32] = &[1, 2, 3];
2019 let r: Arc<[u32]> = Arc::from(s);
2021 assert_eq!(&r[..], [1, 2, 3]);
2025 fn test_clone_from_slice() {
2026 #[derive(Clone, Debug, Eq, PartialEq)]
2029 let s: &[X] = &[X(1), X(2), X(3)];
2030 let r: Arc<[X]> = Arc::from(s);
2032 assert_eq!(&r[..], s);
2037 fn test_clone_from_slice_panic() {
2038 use std::string::{String, ToString};
2040 struct Fail(u32, String);
2042 impl Clone for Fail {
2043 fn clone(&self) -> Fail {
2047 Fail(self.0, self.1.clone())
2052 Fail(0, "foo".to_string()),
2053 Fail(1, "bar".to_string()),
2054 Fail(2, "baz".to_string()),
2057 // Should panic, but not cause memory corruption
2058 let _r: Arc<[Fail]> = Arc::from(s);
2062 fn test_from_box() {
2063 let b: Box<u32> = box 123;
2064 let r: Arc<u32> = Arc::from(b);
2066 assert_eq!(*r, 123);
2070 fn test_from_box_str() {
2071 use std::string::String;
2073 let s = String::from("foo").into_boxed_str();
2074 let r: Arc<str> = Arc::from(s);
2076 assert_eq!(&r[..], "foo");
2080 fn test_from_box_slice() {
2081 let s = vec![1, 2, 3].into_boxed_slice();
2082 let r: Arc<[u32]> = Arc::from(s);
2084 assert_eq!(&r[..], [1, 2, 3]);
2088 fn test_from_box_trait() {
2089 use std::fmt::Display;
2090 use std::string::ToString;
2092 let b: Box<dyn Display> = box 123;
2093 let r: Arc<dyn Display> = Arc::from(b);
2095 assert_eq!(r.to_string(), "123");
2099 fn test_from_box_trait_zero_sized() {
2100 use std::fmt::Debug;
2102 let b: Box<dyn Debug> = box ();
2103 let r: Arc<dyn Debug> = Arc::from(b);
2105 assert_eq!(format!("{:?}", r), "()");
2109 fn test_from_vec() {
2110 let v = vec![1, 2, 3];
2111 let r: Arc<[u32]> = Arc::from(v);
2113 assert_eq!(&r[..], [1, 2, 3]);
2117 fn test_downcast() {
2120 let r1: Arc<dyn Any + Send + Sync> = Arc::new(i32::max_value());
2121 let r2: Arc<dyn Any + Send + Sync> = Arc::new("abc");
2123 assert!(r1.clone().downcast::<u32>().is_err());
2125 let r1i32 = r1.downcast::<i32>();
2126 assert!(r1i32.is_ok());
2127 assert_eq!(r1i32.unwrap(), Arc::new(i32::max_value()));
2129 assert!(r2.clone().downcast::<i32>().is_err());
2131 let r2str = r2.downcast::<&'static str>();
2132 assert!(r2str.is_ok());
2133 assert_eq!(r2str.unwrap(), Arc::new("abc"));
2137 #[stable(feature = "rust1", since = "1.0.0")]
2138 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
2139 fn borrow(&self) -> &T {
2144 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2145 impl<T: ?Sized> AsRef<T> for Arc<T> {
2146 fn as_ref(&self) -> &T {
2151 #[stable(feature = "pin", since = "1.33.0")]
2152 impl<T: ?Sized> Unpin for Arc<T> { }