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
77 use core
::atomic
::Ordering
::{Relaxed, Release, Acquire, SeqCst}
;
79 use core
::cmp
::Ordering
;
80 use core
::mem
::{align_of_val, size_of_val}
;
81 use core
::intrinsics
::drop_in_place
;
83 use core
::nonzero
::NonZero
;
84 use core
::ops
::{Deref, CoerceUnsized}
;
85 use core
::marker
::Unsize
;
86 use core
::hash
::{Hash, Hasher}
;
89 /// An atomically reference counted wrapper for shared state.
93 /// In this example, a large vector of floats is shared between several threads.
94 /// With simple pipes, without `Arc`, a copy would have to be made for each
97 /// When you clone an `Arc<T>`, it will create another pointer to the data and
98 /// increase the reference counter.
101 /// use std::sync::Arc;
105 /// let numbers: Vec<_> = (0..100u32).collect();
106 /// let shared_numbers = Arc::new(numbers);
109 /// let child_numbers = shared_numbers.clone();
111 /// thread::spawn(move || {
112 /// let local_numbers = &child_numbers[..];
114 /// // Work with the local numbers
119 #[unsafe_no_drop_flag]
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub struct Arc
<T
: ?Sized
> {
122 // FIXME #12808: strange name to try to avoid interfering with
123 // field accesses of the contained type via Deref
124 _ptr
: NonZero
<*mut ArcInner
<T
>>,
127 unsafe impl<T
: ?Sized
+ Sync
+ Send
> Send
for Arc
<T
> { }
128 unsafe impl<T
: ?Sized
+ Sync
+ Send
> Sync
for Arc
<T
> { }
130 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<Arc
<U
>> for Arc
<T
> {}
132 /// A weak pointer to an `Arc`.
134 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be
135 /// used to break cycles between `Arc` pointers.
136 #[unsafe_no_drop_flag]
137 #[unstable(feature = "arc_weak",
138 reason
= "Weak pointers may not belong in this module.")]
139 pub struct Weak
<T
: ?Sized
> {
140 // FIXME #12808: strange name to try to avoid interfering with
141 // field accesses of the contained type via Deref
142 _ptr
: NonZero
<*mut ArcInner
<T
>>,
145 unsafe impl<T
: ?Sized
+ Sync
+ Send
> Send
for Weak
<T
> { }
146 unsafe impl<T
: ?Sized
+ Sync
+ Send
> Sync
for Weak
<T
> { }
148 #[stable(feature = "rust1", since = "1.0.0")]
149 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Weak
<T
> {
150 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
155 struct ArcInner
<T
: ?Sized
> {
156 strong
: atomic
::AtomicUsize
,
157 weak
: atomic
::AtomicUsize
,
161 unsafe impl<T
: ?Sized
+ Sync
+ Send
> Send
for ArcInner
<T
> {}
162 unsafe impl<T
: ?Sized
+ Sync
+ Send
> Sync
for ArcInner
<T
> {}
165 /// Constructs a new `Arc<T>`.
170 /// use std::sync::Arc;
172 /// let five = Arc::new(5);
175 #[stable(feature = "rust1", since = "1.0.0")]
176 pub fn new(data
: T
) -> Arc
<T
> {
177 // Start the weak pointer count as 1 which is the weak pointer that's
178 // held by all the strong pointers (kinda), see std/rc.rs for more info
179 let x
: Box
<_
> = box ArcInner
{
180 strong
: atomic
::AtomicUsize
::new(1),
181 weak
: atomic
::AtomicUsize
::new(1),
184 Arc { _ptr: unsafe { NonZero::new(mem::transmute(x)) }
}
188 impl<T
: ?Sized
> Arc
<T
> {
189 /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
194 /// # #![feature(arc_weak)]
195 /// use std::sync::Arc;
197 /// let five = Arc::new(5);
199 /// let weak_five = five.downgrade();
201 #[unstable(feature = "arc_weak",
202 reason
= "Weak pointers may not belong in this module.")]
203 pub fn downgrade(&self) -> Weak
<T
> {
204 // See the clone() impl for why this is relaxed
205 self.inner().weak
.fetch_add(1, Relaxed
);
206 Weak { _ptr: self._ptr }
209 /// Get the number of weak references to this value.
211 #[unstable(feature = "arc_counts")]
212 pub fn weak_count(this
: &Arc
<T
>) -> usize {
213 this
.inner().weak
.load(SeqCst
) - 1
216 /// Get the number of strong references to this value.
218 #[unstable(feature = "arc_counts")]
219 pub fn strong_count(this
: &Arc
<T
>) -> usize {
220 this
.inner().strong
.load(SeqCst
)
224 fn inner(&self) -> &ArcInner
<T
> {
225 // This unsafety is ok because while this arc is alive we're guaranteed
226 // that the inner pointer is valid. Furthermore, we know that the
227 // `ArcInner` structure itself is `Sync` because the inner data is
228 // `Sync` as well, so we're ok loaning out an immutable pointer to these
230 unsafe { &**self._ptr }
233 // Non-inlined part of `drop`.
235 unsafe fn drop_slow(&mut self) {
236 let ptr
= *self._ptr
;
238 // Destroy the data at this time, even though we may not free the box
239 // allocation itself (there may still be weak pointers lying around).
240 drop_in_place(&mut (*ptr
).data
);
242 if self.inner().weak
.fetch_sub(1, Release
) == 1 {
243 atomic
::fence(Acquire
);
244 deallocate(ptr
as *mut u8, size_of_val(&*ptr
), align_of_val(&*ptr
))
249 /// Get the number of weak references to this value.
251 #[unstable(feature = "arc_counts")]
252 #[deprecated(since = "1.2.0", reason = "renamed to Arc::weak_count")]
253 pub fn weak_count
<T
: ?Sized
>(this
: &Arc
<T
>) -> usize { Arc::weak_count(this) }
255 /// Get the number of strong references to this value.
257 #[unstable(feature = "arc_counts")]
258 #[deprecated(since = "1.2.0", reason = "renamed to Arc::strong_count")]
259 pub fn strong_count
<T
: ?Sized
>(this
: &Arc
<T
>) -> usize { Arc::strong_count(this) }
262 /// Returns a mutable reference to the contained value if the `Arc<T>` is unique.
264 /// Returns `None` if the `Arc<T>` is not unique.
266 /// This function is marked **unsafe** because it is racy if weak pointers
272 /// # #![feature(arc_unique, alloc)]
273 /// extern crate alloc;
275 /// use alloc::arc::{Arc, get_mut};
278 /// let mut x = Arc::new(3);
279 /// *get_mut(&mut x).unwrap() = 4;
280 /// assert_eq!(*x, 4);
282 /// let _y = x.clone();
283 /// assert!(get_mut(&mut x).is_none());
288 #[unstable(feature = "arc_unique")]
289 #[deprecated(since = "1.2.0",
290 reason
= "this function is unsafe with weak pointers")]
291 pub unsafe fn get_mut
<T
: ?Sized
>(this
: &mut Arc
<T
>) -> Option
<&mut T
> {
292 // FIXME(#24880) potential race with upgraded weak pointers here
293 if Arc
::strong_count(this
) == 1 && Arc
::weak_count(this
) == 0 {
294 // This unsafety is ok because we're guaranteed that the pointer
295 // returned is the *only* pointer that will ever be returned to T. Our
296 // reference count is guaranteed to be 1 at this point, and we required
297 // the Arc itself to be `mut`, so we're returning the only possible
298 // reference to the inner data.
299 let inner
= &mut **this
._ptr
;
300 Some(&mut inner
.data
)
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<T
: ?Sized
> Clone
for Arc
<T
> {
308 /// Makes a clone of the `Arc<T>`.
310 /// This increases the strong reference count.
315 /// use std::sync::Arc;
317 /// let five = Arc::new(5);
322 fn clone(&self) -> Arc
<T
> {
323 // Using a relaxed ordering is alright here, as knowledge of the
324 // original reference prevents other threads from erroneously deleting
327 // As explained in the [Boost documentation][1], Increasing the
328 // reference counter can always be done with memory_order_relaxed: New
329 // references to an object can only be formed from an existing
330 // reference, and passing an existing reference from one thread to
331 // another must already provide any required synchronization.
333 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
334 self.inner().strong
.fetch_add(1, Relaxed
);
335 Arc { _ptr: self._ptr }
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl<T
: ?Sized
> Deref
for Arc
<T
> {
344 fn deref(&self) -> &T
{
349 impl<T
: Clone
> Arc
<T
> {
350 /// Make a mutable reference from the given `Arc<T>`.
352 /// This is also referred to as a copy-on-write operation because the inner
353 /// data is cloned if the reference count is greater than one.
355 /// This method is marked **unsafe** because it is racy if weak pointers
361 /// # #![feature(arc_unique)]
362 /// use std::sync::Arc;
365 /// let mut five = Arc::new(5);
367 /// let mut_five = five.make_unique();
371 #[unstable(feature = "arc_unique")]
372 #[deprecated(since = "1.2.0",
373 reason
= "this function is unsafe with weak pointers")]
374 pub unsafe fn make_unique(&mut self) -> &mut T
{
375 // FIXME(#24880) potential race with upgraded weak pointers here
377 // Note that we hold a strong reference, which also counts as a weak
378 // reference, so we only clone if there is an additional reference of
380 if self.inner().strong
.load(SeqCst
) != 1 ||
381 self.inner().weak
.load(SeqCst
) != 1 {
382 *self = Arc
::new((**self).clone())
384 // As with `get_mut()`, the unsafety is ok because our reference was
385 // either unique to begin with, or became one upon cloning the contents.
386 let inner
= &mut **self._ptr
;
391 #[stable(feature = "rust1", since = "1.0.0")]
392 impl<T
: ?Sized
> Drop
for Arc
<T
> {
393 /// Drops the `Arc<T>`.
395 /// This will decrement the strong reference count. If the strong reference
396 /// count becomes zero and the only other references are `Weak<T>` ones,
397 /// `drop`s the inner value.
402 /// use std::sync::Arc;
405 /// let five = Arc::new(5);
409 /// drop(five); // explicit drop
412 /// let five = Arc::new(5);
416 /// } // implicit drop
420 // This structure has #[unsafe_no_drop_flag], so this drop glue may run
421 // more than once (but it is guaranteed to be zeroed after the first if
422 // it's run more than once)
423 let ptr
= *self._ptr
;
424 // if ptr.is_null() { return }
425 if ptr
as *mut u8 as usize == 0 || ptr
as *mut u8 as usize == mem
::POST_DROP_USIZE
{
429 // Because `fetch_sub` is already atomic, we do not need to synchronize
430 // with other threads unless we are going to delete the object. This
431 // same logic applies to the below `fetch_sub` to the `weak` count.
432 if self.inner().strong
.fetch_sub(1, Release
) != 1 { return }
434 // This fence is needed to prevent reordering of use of the data and
435 // deletion of the data. Because it is marked `Release`, the decreasing
436 // of the reference count synchronizes with this `Acquire` fence. This
437 // means that use of the data happens before decreasing the reference
438 // count, which happens before this fence, which happens before the
439 // deletion of the data.
441 // As explained in the [Boost documentation][1],
443 // > It is important to enforce any possible access to the object in one
444 // > thread (through an existing reference) to *happen before* deleting
445 // > the object in a different thread. This is achieved by a "release"
446 // > operation after dropping a reference (any access to the object
447 // > through this reference must obviously happened before), and an
448 // > "acquire" operation before deleting the object.
450 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
451 atomic
::fence(Acquire
);
459 #[unstable(feature = "arc_weak",
460 reason
= "Weak pointers may not belong in this module.")]
461 impl<T
: ?Sized
> Weak
<T
> {
462 /// Upgrades a weak reference to a strong reference.
464 /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
466 /// Returns `None` if there were no strong references and the data was
472 /// # #![feature(arc_weak)]
473 /// use std::sync::Arc;
475 /// let five = Arc::new(5);
477 /// let weak_five = five.downgrade();
479 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
481 pub fn upgrade(&self) -> Option
<Arc
<T
>> {
482 // We use a CAS loop to increment the strong count instead of a
483 // fetch_add because once the count hits 0 it must never be above 0.
484 let inner
= self.inner();
486 let n
= inner
.strong
.load(SeqCst
);
487 if n
== 0 { return None }
488 let old
= inner
.strong
.compare_and_swap(n
, n
+ 1, SeqCst
);
489 if old
== n { return Some(Arc { _ptr: self._ptr }
) }
494 fn inner(&self) -> &ArcInner
<T
> {
495 // See comments above for why this is "safe"
496 unsafe { &**self._ptr }
500 #[unstable(feature = "arc_weak",
501 reason
= "Weak pointers may not belong in this module.")]
502 impl<T
: ?Sized
> Clone
for Weak
<T
> {
503 /// Makes a clone of the `Weak<T>`.
505 /// This increases the weak reference count.
510 /// # #![feature(arc_weak)]
511 /// use std::sync::Arc;
513 /// let weak_five = Arc::new(5).downgrade();
515 /// weak_five.clone();
518 fn clone(&self) -> Weak
<T
> {
519 // See comments in Arc::clone() for why this is relaxed
520 self.inner().weak
.fetch_add(1, Relaxed
);
521 Weak { _ptr: self._ptr }
525 #[stable(feature = "rust1", since = "1.0.0")]
526 impl<T
: ?Sized
> Drop
for Weak
<T
> {
527 /// Drops the `Weak<T>`.
529 /// This will decrement the weak reference count.
534 /// # #![feature(arc_weak)]
535 /// use std::sync::Arc;
538 /// let five = Arc::new(5);
539 /// let weak_five = five.downgrade();
543 /// drop(weak_five); // explicit drop
546 /// let five = Arc::new(5);
547 /// let weak_five = five.downgrade();
551 /// } // implicit drop
554 let ptr
= *self._ptr
;
556 // see comments above for why this check is here
557 if ptr
as *mut u8 as usize == 0 || ptr
as *mut u8 as usize == mem
::POST_DROP_USIZE
{
561 // If we find out that we were the last weak pointer, then its time to
562 // deallocate the data entirely. See the discussion in Arc::drop() about
563 // the memory orderings
564 if self.inner().weak
.fetch_sub(1, Release
) == 1 {
565 atomic
::fence(Acquire
);
566 unsafe { deallocate(ptr
as *mut u8,
568 align_of_val(&*ptr
)) }
573 #[stable(feature = "rust1", since = "1.0.0")]
574 impl<T
: ?Sized
+ PartialEq
> PartialEq
for Arc
<T
> {
575 /// Equality for two `Arc<T>`s.
577 /// Two `Arc<T>`s are equal if their inner value are equal.
582 /// use std::sync::Arc;
584 /// let five = Arc::new(5);
586 /// five == Arc::new(5);
588 fn eq(&self, other
: &Arc
<T
>) -> bool { *(*self) == *(*other) }
590 /// Inequality for two `Arc<T>`s.
592 /// Two `Arc<T>`s are unequal if their inner value are unequal.
597 /// use std::sync::Arc;
599 /// let five = Arc::new(5);
601 /// five != Arc::new(5);
603 fn ne(&self, other
: &Arc
<T
>) -> bool { *(*self) != *(*other) }
605 #[stable(feature = "rust1", since = "1.0.0")]
606 impl<T
: ?Sized
+ PartialOrd
> PartialOrd
for Arc
<T
> {
607 /// Partial comparison for two `Arc<T>`s.
609 /// The two are compared by calling `partial_cmp()` on their inner values.
614 /// use std::sync::Arc;
616 /// let five = Arc::new(5);
618 /// five.partial_cmp(&Arc::new(5));
620 fn partial_cmp(&self, other
: &Arc
<T
>) -> Option
<Ordering
> {
621 (**self).partial_cmp(&**other
)
624 /// Less-than comparison for two `Arc<T>`s.
626 /// The two are compared by calling `<` on their inner values.
631 /// use std::sync::Arc;
633 /// let five = Arc::new(5);
635 /// five < Arc::new(5);
637 fn lt(&self, other
: &Arc
<T
>) -> bool { *(*self) < *(*other) }
639 /// 'Less-than or equal to' comparison for two `Arc<T>`s.
641 /// The two are compared by calling `<=` on their inner values.
646 /// use std::sync::Arc;
648 /// let five = Arc::new(5);
650 /// five <= Arc::new(5);
652 fn le(&self, other
: &Arc
<T
>) -> bool { *(*self) <= *(*other) }
654 /// Greater-than comparison for two `Arc<T>`s.
656 /// The two are compared by calling `>` on their inner values.
661 /// use std::sync::Arc;
663 /// let five = Arc::new(5);
665 /// five > Arc::new(5);
667 fn gt(&self, other
: &Arc
<T
>) -> bool { *(*self) > *(*other) }
669 /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
671 /// The two are compared by calling `>=` on their inner values.
676 /// use std::sync::Arc;
678 /// let five = Arc::new(5);
680 /// five >= Arc::new(5);
682 fn ge(&self, other
: &Arc
<T
>) -> bool { *(*self) >= *(*other) }
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl<T
: ?Sized
+ Ord
> Ord
for Arc
<T
> {
686 fn cmp(&self, other
: &Arc
<T
>) -> Ordering { (**self).cmp(&**other) }
688 #[stable(feature = "rust1", since = "1.0.0")]
689 impl<T
: ?Sized
+ Eq
> Eq
for Arc
<T
> {}
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl<T
: ?Sized
+ fmt
::Display
> fmt
::Display
for Arc
<T
> {
693 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
694 fmt
::Display
::fmt(&**self, f
)
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Arc
<T
> {
700 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
701 fmt
::Debug
::fmt(&**self, f
)
705 #[stable(feature = "rust1", since = "1.0.0")]
706 impl<T
> fmt
::Pointer
for Arc
<T
> {
707 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
708 fmt
::Pointer
::fmt(&*self._ptr
, f
)
712 #[stable(feature = "rust1", since = "1.0.0")]
713 impl<T
: Default
> Default
for Arc
<T
> {
714 #[stable(feature = "rust1", since = "1.0.0")]
715 fn default() -> Arc
<T
> { Arc::new(Default::default()) }
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl<T
: ?Sized
+ Hash
> Hash
for Arc
<T
> {
720 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
727 use std
::clone
::Clone
;
728 use std
::sync
::mpsc
::channel
;
731 use std
::option
::Option
;
732 use std
::option
::Option
::{Some, None}
;
733 use std
::sync
::atomic
;
734 use std
::sync
::atomic
::Ordering
::{Acquire, SeqCst}
;
737 use super::{Arc, Weak, get_mut, weak_count, strong_count}
;
738 use std
::sync
::Mutex
;
740 struct Canary(*mut atomic
::AtomicUsize
);
748 (*c
).fetch_add(1, SeqCst
);
756 fn manually_share_arc() {
757 let v
= vec
!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
758 let arc_v
= Arc
::new(v
);
760 let (tx
, rx
) = channel();
762 let _t
= thread
::spawn(move || {
763 let arc_v
: Arc
<Vec
<i32>> = rx
.recv().unwrap();
764 assert_eq
!((*arc_v
)[3], 4);
767 tx
.send(arc_v
.clone()).unwrap();
769 assert_eq
!((*arc_v
)[2], 3);
770 assert_eq
!((*arc_v
)[4], 5);
774 fn test_arc_get_mut() {
776 let mut x
= Arc
::new(3);
777 *get_mut(&mut x
).unwrap() = 4;
780 assert
!(get_mut(&mut x
).is_none());
782 assert
!(get_mut(&mut x
).is_some());
783 let _w
= x
.downgrade();
784 assert
!(get_mut(&mut x
).is_none());
789 fn test_cowarc_clone_make_unique() {
791 let mut cow0
= Arc
::new(75);
792 let mut cow1
= cow0
.clone();
793 let mut cow2
= cow1
.clone();
795 assert
!(75 == *cow0
.make_unique());
796 assert
!(75 == *cow1
.make_unique());
797 assert
!(75 == *cow2
.make_unique());
799 *cow0
.make_unique() += 1;
800 *cow1
.make_unique() += 2;
801 *cow2
.make_unique() += 3;
803 assert
!(76 == *cow0
);
804 assert
!(77 == *cow1
);
805 assert
!(78 == *cow2
);
807 // none should point to the same backing memory
808 assert
!(*cow0
!= *cow1
);
809 assert
!(*cow0
!= *cow2
);
810 assert
!(*cow1
!= *cow2
);
815 fn test_cowarc_clone_unique2() {
816 let mut cow0
= Arc
::new(75);
817 let cow1
= cow0
.clone();
818 let cow2
= cow1
.clone();
820 assert
!(75 == *cow0
);
821 assert
!(75 == *cow1
);
822 assert
!(75 == *cow2
);
825 *cow0
.make_unique() += 1;
828 assert
!(76 == *cow0
);
829 assert
!(75 == *cow1
);
830 assert
!(75 == *cow2
);
832 // cow1 and cow2 should share the same contents
833 // cow0 should have a unique reference
834 assert
!(*cow0
!= *cow1
);
835 assert
!(*cow0
!= *cow2
);
836 assert
!(*cow1
== *cow2
);
840 fn test_cowarc_clone_weak() {
841 let mut cow0
= Arc
::new(75);
842 let cow1_weak
= cow0
.downgrade();
844 assert
!(75 == *cow0
);
845 assert
!(75 == *cow1_weak
.upgrade().unwrap());
848 *cow0
.make_unique() += 1;
851 assert
!(76 == *cow0
);
852 assert
!(cow1_weak
.upgrade().is_none());
858 let y
= x
.downgrade();
859 assert
!(y
.upgrade().is_some());
865 let y
= x
.downgrade();
867 assert
!(y
.upgrade().is_none());
871 fn weak_self_cyclic() {
873 x
: Mutex
<Option
<Weak
<Cycle
>>>
876 let a
= Arc
::new(Cycle { x: Mutex::new(None) }
);
877 let b
= a
.clone().downgrade();
878 *a
.x
.lock().unwrap() = Some(b
);
880 // hopefully we don't double-free (or leak)...
885 let mut canary
= atomic
::AtomicUsize
::new(0);
886 let x
= Arc
::new(Canary(&mut canary
as *mut atomic
::AtomicUsize
));
888 assert
!(canary
.load(Acquire
) == 1);
893 let mut canary
= atomic
::AtomicUsize
::new(0);
894 let arc
= Arc
::new(Canary(&mut canary
as *mut atomic
::AtomicUsize
));
895 let arc_weak
= arc
.downgrade();
896 assert
!(canary
.load(Acquire
) == 0);
898 assert
!(canary
.load(Acquire
) == 1);
903 fn test_strong_count() {
904 let a
= Arc
::new(0u32);
905 assert
!(strong_count(&a
) == 1);
906 let w
= a
.downgrade();
907 assert
!(strong_count(&a
) == 1);
908 let b
= w
.upgrade().expect("");
909 assert
!(strong_count(&b
) == 2);
910 assert
!(strong_count(&a
) == 2);
913 assert
!(strong_count(&b
) == 1);
915 assert
!(strong_count(&b
) == 2);
916 assert
!(strong_count(&c
) == 2);
920 fn test_weak_count() {
921 let a
= Arc
::new(0u32);
922 assert
!(strong_count(&a
) == 1);
923 assert
!(weak_count(&a
) == 0);
924 let w
= a
.downgrade();
925 assert
!(strong_count(&a
) == 1);
926 assert
!(weak_count(&a
) == 1);
928 assert
!(weak_count(&a
) == 2);
931 assert
!(strong_count(&a
) == 1);
932 assert
!(weak_count(&a
) == 0);
934 assert
!(strong_count(&a
) == 2);
935 assert
!(weak_count(&a
) == 0);
936 let d
= c
.downgrade();
937 assert
!(weak_count(&c
) == 1);
938 assert
!(strong_count(&c
) == 2);
947 let a
= Arc
::new(5u32);
948 assert_eq
!(format
!("{:?}", a
), "5");
951 // Make sure deriving works with Arc<T>
952 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
953 struct Foo { inner: Arc<i32> }
957 let x
: Arc
<[i32]> = Arc
::new([1, 2, 3]);
958 assert_eq
!(format
!("{:?}", x
), "[1, 2, 3]");
959 let y
= x
.clone().downgrade();
961 assert
!(y
.upgrade().is_none());