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.
13 //! Threadsafe reference-counted boxes (the `Arc<T>` type).
15 //! The `Arc<T>` type provides shared ownership of an immutable value. Destruction is
16 //! deterministic, and will occur as soon as the last owner is gone. It is marked as `Send` because
17 //! it uses atomic reference counting.
19 //! If you do not need thread-safety, and just need shared ownership, consider the [`Rc<T>`
20 //! type](../rc/struct.Rc.html). It is the same as `Arc<T>`, but does not use atomics, making it
21 //! both thread-unsafe as well as significantly faster when updating the reference count.
23 //! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer to the box. A
24 //! `Weak<T>` pointer can be upgraded to an `Arc<T>` pointer, but will return `None` if the value
25 //! has already been dropped.
27 //! For example, a tree with parent pointers can be represented by putting the nodes behind strong
28 //! `Arc<T>` pointers, and then storing the parent pointers as `Weak<T>` pointers.
32 //! Sharing some immutable data between tasks:
35 //! use std::sync::Arc;
36 //! use std::thread::Thread;
38 //! let five = Arc::new(5i);
40 //! for _ in range(0u, 10) {
41 //! let five = five.clone();
43 //! Thread::spawn(move || {
44 //! println!("{:?}", five);
49 //! Sharing mutable data safely between tasks with a `Mutex`:
52 //! use std::sync::{Arc, Mutex};
53 //! use std::thread::Thread;
55 //! let five = Arc::new(Mutex::new(5i));
57 //! for _ in range(0u, 10) {
58 //! let five = five.clone();
60 //! Thread::spawn(move || {
61 //! let mut number = five.lock().unwrap();
65 //! println!("{}", *number); // prints 6
73 use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
74 use core::borrow::BorrowFrom;
76 use core::cmp::{Ordering};
77 use core::default::Default;
78 use core::mem::{min_align_of, size_of};
80 use core::nonzero::NonZero;
83 use core::hash::{Hash, Hasher};
86 /// An atomically reference counted wrapper for shared state.
90 /// In this example, a large vector of floats is shared between several tasks. With simple pipes,
91 /// without `Arc`, a copy would have to be made for each task.
94 /// use std::sync::Arc;
95 /// use std::thread::Thread;
98 /// let numbers: Vec<_> = range(0, 100u32).map(|i| i as f32).collect();
99 /// let shared_numbers = Arc::new(numbers);
101 /// for _ in range(0u, 10) {
102 /// let child_numbers = shared_numbers.clone();
104 /// Thread::spawn(move || {
105 /// let local_numbers = child_numbers.as_slice();
107 /// // Work with the local numbers
112 #[unsafe_no_drop_flag]
115 // FIXME #12808: strange name to try to avoid interfering with
116 // field accesses of the contained type via Deref
117 _ptr: NonZero<*mut ArcInner<T>>,
120 unsafe impl<T: Sync + Send> Send for Arc<T> { }
121 unsafe impl<T: Sync + Send> Sync for Arc<T> { }
124 /// A weak pointer to an `Arc`.
126 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be used to break cycles
127 /// between `Arc` pointers.
128 #[unsafe_no_drop_flag]
129 #[unstable = "Weak pointers may not belong in this module."]
131 // FIXME #12808: strange name to try to avoid interfering with
132 // field accesses of the contained type via Deref
133 _ptr: NonZero<*mut ArcInner<T>>,
136 unsafe impl<T: Sync + Send> Send for Weak<T> { }
137 unsafe impl<T: Sync + Send> Sync for Weak<T> { }
140 strong: atomic::AtomicUsize,
141 weak: atomic::AtomicUsize,
145 unsafe impl<T: Sync + Send> Send for ArcInner<T> {}
146 unsafe impl<T: Sync + Send> Sync for ArcInner<T> {}
149 /// Constructs a new `Arc<T>`.
154 /// use std::sync::Arc;
156 /// let five = Arc::new(5i);
160 pub fn new(data: T) -> Arc<T> {
161 // Start the weak pointer count as 1 which is the weak pointer that's
162 // held by all the strong pointers (kinda), see std/rc.rs for more info
163 let x = box ArcInner {
164 strong: atomic::AtomicUsize::new(1),
165 weak: atomic::AtomicUsize::new(1),
168 Arc { _ptr: unsafe { NonZero::new(mem::transmute(x)) } }
171 /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
176 /// use std::sync::Arc;
178 /// let five = Arc::new(5i);
180 /// let weak_five = five.downgrade();
182 #[unstable = "Weak pointers may not belong in this module."]
183 pub fn downgrade(&self) -> Weak<T> {
184 // See the clone() impl for why this is relaxed
185 self.inner().weak.fetch_add(1, Relaxed);
186 Weak { _ptr: self._ptr }
192 fn inner(&self) -> &ArcInner<T> {
193 // This unsafety is ok because while this arc is alive we're guaranteed that the inner
194 // pointer is valid. Furthermore, we know that the `ArcInner` structure itself is `Sync`
195 // because the inner data is `Sync` as well, so we're ok loaning out an immutable pointer
196 // to these contents.
197 unsafe { &**self._ptr }
201 /// Get the number of weak references to this value.
204 pub fn weak_count<T>(this: &Arc<T>) -> uint { this.inner().weak.load(SeqCst) - 1 }
206 /// Get the number of strong references to this value.
209 pub fn strong_count<T>(this: &Arc<T>) -> uint { this.inner().strong.load(SeqCst) }
212 impl<T> Clone for Arc<T> {
213 /// Makes a clone of the `Arc<T>`.
215 /// This increases the strong reference count.
220 /// use std::sync::Arc;
222 /// let five = Arc::new(5i);
227 fn clone(&self) -> Arc<T> {
228 // Using a relaxed ordering is alright here, as knowledge of the original reference
229 // prevents other threads from erroneously deleting the object.
231 // As explained in the [Boost documentation][1], Increasing the reference counter can
232 // always be done with memory_order_relaxed: New references to an object can only be formed
233 // from an existing reference, and passing an existing reference from one thread to another
234 // must already provide any required synchronization.
236 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
237 self.inner().strong.fetch_add(1, Relaxed);
238 Arc { _ptr: self._ptr }
242 impl<T> BorrowFrom<Arc<T>> for T {
243 fn borrow_from(owned: &Arc<T>) -> &T {
249 impl<T> Deref for Arc<T> {
253 fn deref(&self) -> &T {
258 impl<T: Send + Sync + Clone> Arc<T> {
259 /// Make a mutable reference from the given `Arc<T>`.
261 /// This is also referred to as a copy-on-write operation because the inner data is cloned if
262 /// the reference count is greater than one.
267 /// use std::sync::Arc;
269 /// let mut five = Arc::new(5i);
271 /// let mut_five = five.make_unique();
275 pub fn make_unique(&mut self) -> &mut T {
276 // Note that we hold a strong reference, which also counts as a weak reference, so we only
277 // clone if there is an additional reference of either kind.
278 if self.inner().strong.load(SeqCst) != 1 ||
279 self.inner().weak.load(SeqCst) != 1 {
280 *self = Arc::new((**self).clone())
282 // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
283 // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
284 // this point, and we required the Arc itself to be `mut`, so we're returning the only
285 // possible reference to the inner data.
286 let inner = unsafe { &mut **self._ptr };
293 impl<T: Sync + Send> Drop for Arc<T> {
294 /// Drops the `Arc<T>`.
296 /// This will decrement the strong reference count. If the strong reference count becomes zero
297 /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
302 /// use std::sync::Arc;
305 /// let five = Arc::new(5i);
309 /// drop(five); // explict drop
312 /// let five = Arc::new(5i);
316 /// } // implicit drop
319 // This structure has #[unsafe_no_drop_flag], so this drop glue may run more than once (but
320 // it is guaranteed to be zeroed after the first if it's run more than once)
321 let ptr = *self._ptr;
322 if ptr.is_null() { return }
324 // Because `fetch_sub` is already atomic, we do not need to synchronize with other threads
325 // unless we are going to delete the object. This same logic applies to the below
326 // `fetch_sub` to the `weak` count.
327 if self.inner().strong.fetch_sub(1, Release) != 1 { return }
329 // This fence is needed to prevent reordering of use of the data and deletion of the data.
330 // Because it is marked `Release`, the decreasing of the reference count synchronizes with
331 // this `Acquire` fence. This means that use of the data happens before decreasing the
332 // reference count, which happens before this fence, which happens before the deletion of
335 // As explained in the [Boost documentation][1],
337 // > It is important to enforce any possible access to the object in one thread (through an
338 // > existing reference) to *happen before* deleting the object in a different thread. This
339 // > is achieved by a "release" operation after dropping a reference (any access to the
340 // > object through this reference must obviously happened before), and an "acquire"
341 // > operation before deleting the object.
343 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
344 atomic::fence(Acquire);
346 // Destroy the data at this time, even though we may not free the box allocation itself
347 // (there may still be weak pointers lying around).
348 unsafe { drop(ptr::read(&self.inner().data)); }
350 if self.inner().weak.fetch_sub(1, Release) == 1 {
351 atomic::fence(Acquire);
352 unsafe { deallocate(ptr as *mut u8, size_of::<ArcInner<T>>(),
353 min_align_of::<ArcInner<T>>()) }
358 #[unstable = "Weak pointers may not belong in this module."]
359 impl<T: Sync + Send> Weak<T> {
360 /// Upgrades a weak reference to a strong reference.
362 /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
364 /// Returns `None` if there were no strong references and the data was destroyed.
369 /// use std::sync::Arc;
371 /// let five = Arc::new(5i);
373 /// let weak_five = five.downgrade();
375 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
377 pub fn upgrade(&self) -> Option<Arc<T>> {
378 // We use a CAS loop to increment the strong count instead of a fetch_add because once the
379 // count hits 0 is must never be above 0.
380 let inner = self.inner();
382 let n = inner.strong.load(SeqCst);
383 if n == 0 { return None }
384 let old = inner.strong.compare_and_swap(n, n + 1, SeqCst);
385 if old == n { return Some(Arc { _ptr: self._ptr }) }
390 fn inner(&self) -> &ArcInner<T> {
391 // See comments above for why this is "safe"
392 unsafe { &**self._ptr }
396 #[unstable = "Weak pointers may not belong in this module."]
397 impl<T: Sync + Send> Clone for Weak<T> {
398 /// Makes a clone of the `Weak<T>`.
400 /// This increases the weak reference count.
405 /// use std::sync::Arc;
407 /// let weak_five = Arc::new(5i).downgrade();
409 /// weak_five.clone();
412 fn clone(&self) -> Weak<T> {
413 // See comments in Arc::clone() for why this is relaxed
414 self.inner().weak.fetch_add(1, Relaxed);
415 Weak { _ptr: self._ptr }
421 impl<T: Sync + Send> Drop for Weak<T> {
422 /// Drops the `Weak<T>`.
424 /// This will decrement the weak reference count.
429 /// use std::sync::Arc;
432 /// let five = Arc::new(5i);
433 /// let weak_five = five.downgrade();
437 /// drop(weak_five); // explict drop
440 /// let five = Arc::new(5i);
441 /// let weak_five = five.downgrade();
445 /// } // implicit drop
448 let ptr = *self._ptr;
450 // see comments above for why this check is here
451 if ptr.is_null() { return }
453 // If we find out that we were the last weak pointer, then its time to deallocate the data
454 // entirely. See the discussion in Arc::drop() about the memory orderings
455 if self.inner().weak.fetch_sub(1, Release) == 1 {
456 atomic::fence(Acquire);
457 unsafe { deallocate(ptr as *mut u8, size_of::<ArcInner<T>>(),
458 min_align_of::<ArcInner<T>>()) }
464 impl<T: PartialEq> PartialEq for Arc<T> {
465 /// Equality for two `Arc<T>`s.
467 /// Two `Arc<T>`s are equal if their inner value are equal.
472 /// use std::sync::Arc;
474 /// let five = Arc::new(5i);
476 /// five == Arc::new(5i);
478 fn eq(&self, other: &Arc<T>) -> bool { *(*self) == *(*other) }
480 /// Inequality for two `Arc<T>`s.
482 /// Two `Arc<T>`s are unequal if their inner value are unequal.
487 /// use std::sync::Arc;
489 /// let five = Arc::new(5i);
491 /// five != Arc::new(5i);
493 fn ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) }
496 impl<T: PartialOrd> PartialOrd for Arc<T> {
497 /// Partial comparison for two `Arc<T>`s.
499 /// The two are compared by calling `partial_cmp()` on their inner values.
504 /// use std::sync::Arc;
506 /// let five = Arc::new(5i);
508 /// five.partial_cmp(&Arc::new(5i));
510 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
511 (**self).partial_cmp(&**other)
514 /// Less-than comparison for two `Arc<T>`s.
516 /// The two are compared by calling `<` on their inner values.
521 /// use std::sync::Arc;
523 /// let five = Arc::new(5i);
525 /// five < Arc::new(5i);
527 fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) }
529 /// 'Less-than or equal to' comparison for two `Arc<T>`s.
531 /// The two are compared by calling `<=` on their inner values.
536 /// use std::sync::Arc;
538 /// let five = Arc::new(5i);
540 /// five <= Arc::new(5i);
542 fn le(&self, other: &Arc<T>) -> bool { *(*self) <= *(*other) }
544 /// Greater-than comparison for two `Arc<T>`s.
546 /// The two are compared by calling `>` on their inner values.
551 /// use std::sync::Arc;
553 /// let five = Arc::new(5i);
555 /// five > Arc::new(5i);
557 fn gt(&self, other: &Arc<T>) -> bool { *(*self) > *(*other) }
559 /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
561 /// The two are compared by calling `>=` on their inner values.
566 /// use std::sync::Arc;
568 /// let five = Arc::new(5i);
570 /// five >= Arc::new(5i);
572 fn ge(&self, other: &Arc<T>) -> bool { *(*self) >= *(*other) }
575 impl<T: Ord> Ord for Arc<T> {
576 fn cmp(&self, other: &Arc<T>) -> Ordering { (**self).cmp(&**other) }
579 impl<T: Eq> Eq for Arc<T> {}
582 impl<T: fmt::Display> fmt::Display for Arc<T> {
583 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
584 fmt::Display::fmt(&**self, f)
589 impl<T: fmt::Debug> fmt::Debug for Arc<T> {
590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
591 fmt::Debug::fmt(&**self, f)
596 impl<T: Default + Sync + Send> Default for Arc<T> {
598 fn default() -> Arc<T> { Arc::new(Default::default()) }
601 impl<H: Hasher, T: Hash<H>> Hash<H> for Arc<T> {
602 fn hash(&self, state: &mut H) {
610 use std::clone::Clone;
611 use std::sync::mpsc::channel;
614 use std::option::Option;
615 use std::option::Option::{Some, None};
616 use std::sync::atomic;
617 use std::sync::atomic::Ordering::{Acquire, SeqCst};
618 use std::thread::Thread;
620 use super::{Arc, Weak, weak_count, strong_count};
621 use std::sync::Mutex;
623 struct Canary(*mut atomic::AtomicUsize);
631 (*c).fetch_add(1, SeqCst);
639 fn manually_share_arc() {
640 let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
641 let arc_v = Arc::new(v);
643 let (tx, rx) = channel();
645 let _t = Thread::spawn(move || {
646 let arc_v: Arc<Vec<int>> = rx.recv().unwrap();
647 assert_eq!((*arc_v)[3], 4);
650 tx.send(arc_v.clone()).unwrap();
652 assert_eq!((*arc_v)[2], 3);
653 assert_eq!((*arc_v)[4], 5);
657 fn test_cowarc_clone_make_unique() {
658 let mut cow0 = Arc::new(75u);
659 let mut cow1 = cow0.clone();
660 let mut cow2 = cow1.clone();
662 assert!(75 == *cow0.make_unique());
663 assert!(75 == *cow1.make_unique());
664 assert!(75 == *cow2.make_unique());
666 *cow0.make_unique() += 1;
667 *cow1.make_unique() += 2;
668 *cow2.make_unique() += 3;
670 assert!(76 == *cow0);
671 assert!(77 == *cow1);
672 assert!(78 == *cow2);
674 // none should point to the same backing memory
675 assert!(*cow0 != *cow1);
676 assert!(*cow0 != *cow2);
677 assert!(*cow1 != *cow2);
681 fn test_cowarc_clone_unique2() {
682 let mut cow0 = Arc::new(75u);
683 let cow1 = cow0.clone();
684 let cow2 = cow1.clone();
686 assert!(75 == *cow0);
687 assert!(75 == *cow1);
688 assert!(75 == *cow2);
690 *cow0.make_unique() += 1;
692 assert!(76 == *cow0);
693 assert!(75 == *cow1);
694 assert!(75 == *cow2);
696 // cow1 and cow2 should share the same contents
697 // cow0 should have a unique reference
698 assert!(*cow0 != *cow1);
699 assert!(*cow0 != *cow2);
700 assert!(*cow1 == *cow2);
704 fn test_cowarc_clone_weak() {
705 let mut cow0 = Arc::new(75u);
706 let cow1_weak = cow0.downgrade();
708 assert!(75 == *cow0);
709 assert!(75 == *cow1_weak.upgrade().unwrap());
711 *cow0.make_unique() += 1;
713 assert!(76 == *cow0);
714 assert!(cow1_weak.upgrade().is_none());
719 let x = Arc::new(5i);
720 let y = x.downgrade();
721 assert!(y.upgrade().is_some());
726 let x = Arc::new(5i);
727 let y = x.downgrade();
729 assert!(y.upgrade().is_none());
733 fn weak_self_cyclic() {
735 x: Mutex<Option<Weak<Cycle>>>
738 let a = Arc::new(Cycle { x: Mutex::new(None) });
739 let b = a.clone().downgrade();
740 *a.x.lock().unwrap() = Some(b);
742 // hopefully we don't double-free (or leak)...
747 let mut canary = atomic::AtomicUsize::new(0);
748 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
750 assert!(canary.load(Acquire) == 1);
755 let mut canary = atomic::AtomicUsize::new(0);
756 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
757 let arc_weak = arc.downgrade();
758 assert!(canary.load(Acquire) == 0);
760 assert!(canary.load(Acquire) == 1);
765 fn test_strong_count() {
766 let a = Arc::new(0u32);
767 assert!(strong_count(&a) == 1);
768 let w = a.downgrade();
769 assert!(strong_count(&a) == 1);
770 let b = w.upgrade().expect("");
771 assert!(strong_count(&b) == 2);
772 assert!(strong_count(&a) == 2);
775 assert!(strong_count(&b) == 1);
777 assert!(strong_count(&b) == 2);
778 assert!(strong_count(&c) == 2);
782 fn test_weak_count() {
783 let a = Arc::new(0u32);
784 assert!(strong_count(&a) == 1);
785 assert!(weak_count(&a) == 0);
786 let w = a.downgrade();
787 assert!(strong_count(&a) == 1);
788 assert!(weak_count(&a) == 1);
790 assert!(weak_count(&a) == 2);
793 assert!(strong_count(&a) == 1);
794 assert!(weak_count(&a) == 0);
796 assert!(strong_count(&a) == 2);
797 assert!(weak_count(&a) == 0);
798 let d = c.downgrade();
799 assert!(weak_count(&c) == 1);
800 assert!(strong_count(&c) == 2);
809 let a = Arc::new(5u32);
810 assert_eq!(format!("{:?}", a), "5");
813 // Make sure deriving works with Arc<T>
814 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Show, Default)]
815 struct Foo { inner: Arc<int> }