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 tasks:
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 tasks with a `Mutex`:
54 //! use std::sync::{Arc, Mutex};
57 //! let five = Arc::new(Mutex::new(5));
60 //! let five = five.clone();
62 //! thread::spawn(move || {
63 //! let mut number = five.lock().unwrap();
67 //! println!("{}", *number); // prints 6
75 use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
77 use core::cmp::{Ordering};
78 use core::default::Default;
79 use core::mem::{min_align_of, size_of};
81 use core::nonzero::NonZero;
84 use core::hash::{Hash, Hasher};
87 /// An atomically reference counted wrapper for shared state.
91 /// In this example, a large vector of floats is shared between several tasks.
92 /// With simple pipes, without `Arc`, a copy would have to be made for each
96 /// use std::sync::Arc;
100 /// let numbers: Vec<_> = (0..100u32).map(|i| i as f32).collect();
101 /// let shared_numbers = Arc::new(numbers);
104 /// let child_numbers = shared_numbers.clone();
106 /// thread::spawn(move || {
107 /// let local_numbers = child_numbers.as_slice();
109 /// // Work with the local numbers
114 #[unsafe_no_drop_flag]
115 #[stable(feature = "rust1", since = "1.0.0")]
117 // FIXME #12808: strange name to try to avoid interfering with
118 // field accesses of the contained type via Deref
119 _ptr: NonZero<*mut ArcInner<T>>,
122 unsafe impl<T: Sync + Send> Send for Arc<T> { }
123 unsafe impl<T: Sync + Send> Sync for Arc<T> { }
126 /// A weak pointer to an `Arc`.
128 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be used to break cycles
129 /// between `Arc` pointers.
130 #[unsafe_no_drop_flag]
131 #[unstable(feature = "alloc",
132 reason = "Weak pointers may not belong in this module.")]
134 // FIXME #12808: strange name to try to avoid interfering with
135 // field accesses of the contained type via Deref
136 _ptr: NonZero<*mut ArcInner<T>>,
139 unsafe impl<T: Sync + Send> Send for Weak<T> { }
140 unsafe impl<T: Sync + Send> Sync for Weak<T> { }
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl<T: fmt::Debug> fmt::Debug for Weak<T> {
144 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150 strong: atomic::AtomicUsize,
151 weak: atomic::AtomicUsize,
155 unsafe impl<T: Sync + Send> Send for ArcInner<T> {}
156 unsafe impl<T: Sync + Send> Sync for ArcInner<T> {}
159 /// Constructs a new `Arc<T>`.
164 /// use std::sync::Arc;
166 /// let five = Arc::new(5);
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub fn new(data: T) -> Arc<T> {
171 // Start the weak pointer count as 1 which is the weak pointer that's
172 // held by all the strong pointers (kinda), see std/rc.rs for more info
173 let x = box ArcInner {
174 strong: atomic::AtomicUsize::new(1),
175 weak: atomic::AtomicUsize::new(1),
178 Arc { _ptr: unsafe { NonZero::new(mem::transmute(x)) } }
181 /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
186 /// use std::sync::Arc;
188 /// let five = Arc::new(5);
190 /// let weak_five = five.downgrade();
192 #[unstable(feature = "alloc",
193 reason = "Weak pointers may not belong in this module.")]
194 pub fn downgrade(&self) -> Weak<T> {
195 // See the clone() impl for why this is relaxed
196 self.inner().weak.fetch_add(1, Relaxed);
197 Weak { _ptr: self._ptr }
203 fn inner(&self) -> &ArcInner<T> {
204 // This unsafety is ok because while this arc is alive we're guaranteed that the inner
205 // pointer is valid. Furthermore, we know that the `ArcInner` structure itself is `Sync`
206 // because the inner data is `Sync` as well, so we're ok loaning out an immutable pointer
207 // to these contents.
208 unsafe { &**self._ptr }
212 /// Get the number of weak references to this value.
214 #[unstable(feature = "alloc")]
215 pub fn weak_count<T>(this: &Arc<T>) -> usize { this.inner().weak.load(SeqCst) - 1 }
217 /// Get the number of strong references to this value.
219 #[unstable(feature = "alloc")]
220 pub fn strong_count<T>(this: &Arc<T>) -> usize { this.inner().strong.load(SeqCst) }
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl<T> Clone for Arc<T> {
224 /// Makes a clone of the `Arc<T>`.
226 /// This increases the strong reference count.
231 /// use std::sync::Arc;
233 /// let five = Arc::new(5);
238 fn clone(&self) -> Arc<T> {
239 // Using a relaxed ordering is alright here, as knowledge of the original reference
240 // prevents other threads from erroneously deleting the object.
242 // As explained in the [Boost documentation][1], Increasing the reference counter can
243 // always be done with memory_order_relaxed: New references to an object can only be formed
244 // from an existing reference, and passing an existing reference from one thread to another
245 // must already provide any required synchronization.
247 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
248 self.inner().strong.fetch_add(1, Relaxed);
249 Arc { _ptr: self._ptr }
253 #[stable(feature = "rust1", since = "1.0.0")]
254 impl<T> Deref for Arc<T> {
258 fn deref(&self) -> &T {
263 impl<T: Send + Sync + Clone> Arc<T> {
264 /// Make a mutable reference from the given `Arc<T>`.
266 /// This is also referred to as a copy-on-write operation because the inner data is cloned if
267 /// the reference count is greater than one.
272 /// use std::sync::Arc;
274 /// let mut five = Arc::new(5);
276 /// let mut_five = five.make_unique();
279 #[unstable(feature = "alloc")]
280 pub fn make_unique(&mut self) -> &mut T {
281 // Note that we hold a strong reference, which also counts as a weak reference, so we only
282 // clone if there is an additional reference of either kind.
283 if self.inner().strong.load(SeqCst) != 1 ||
284 self.inner().weak.load(SeqCst) != 1 {
285 *self = Arc::new((**self).clone())
287 // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
288 // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
289 // this point, and we required the Arc itself to be `mut`, so we're returning the only
290 // possible reference to the inner data.
291 let inner = unsafe { &mut **self._ptr };
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl<T: Sync + Send> Drop for Arc<T> {
299 /// Drops the `Arc<T>`.
301 /// This will decrement the strong reference count. If the strong reference count becomes zero
302 /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
307 /// use std::sync::Arc;
310 /// let five = Arc::new(5);
314 /// drop(five); // explicit drop
317 /// let five = Arc::new(5);
321 /// } // implicit drop
324 // This structure has #[unsafe_no_drop_flag], so this drop glue may run more than once (but
325 // it is guaranteed to be zeroed after the first if it's run more than once)
326 let ptr = *self._ptr;
327 if ptr.is_null() { return }
329 // Because `fetch_sub` is already atomic, we do not need to synchronize with other threads
330 // unless we are going to delete the object. This same logic applies to the below
331 // `fetch_sub` to the `weak` count.
332 if self.inner().strong.fetch_sub(1, Release) != 1 { return }
334 // This fence is needed to prevent reordering of use of the data and deletion of the data.
335 // Because it is marked `Release`, the decreasing of the reference count synchronizes with
336 // this `Acquire` fence. This means that use of the data happens before decreasing the
337 // reference count, which happens before this fence, which happens before the deletion of
340 // As explained in the [Boost documentation][1],
342 // > It is important to enforce any possible access to the object in one thread (through an
343 // > existing reference) to *happen before* deleting the object in a different thread. This
344 // > is achieved by a "release" operation after dropping a reference (any access to the
345 // > object through this reference must obviously happened before), and an "acquire"
346 // > operation before deleting the object.
348 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
349 atomic::fence(Acquire);
351 // Destroy the data at this time, even though we may not free the box allocation itself
352 // (there may still be weak pointers lying around).
353 unsafe { drop(ptr::read(&self.inner().data)); }
355 if self.inner().weak.fetch_sub(1, Release) == 1 {
356 atomic::fence(Acquire);
357 unsafe { deallocate(ptr as *mut u8, size_of::<ArcInner<T>>(),
358 min_align_of::<ArcInner<T>>()) }
363 #[unstable(feature = "alloc",
364 reason = "Weak pointers may not belong in this module.")]
365 impl<T: Sync + Send> Weak<T> {
366 /// Upgrades a weak reference to a strong reference.
368 /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
370 /// Returns `None` if there were no strong references and the data was destroyed.
375 /// use std::sync::Arc;
377 /// let five = Arc::new(5);
379 /// let weak_five = five.downgrade();
381 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
383 pub fn upgrade(&self) -> Option<Arc<T>> {
384 // We use a CAS loop to increment the strong count instead of a fetch_add because once the
385 // count hits 0 is must never be above 0.
386 let inner = self.inner();
388 let n = inner.strong.load(SeqCst);
389 if n == 0 { return None }
390 let old = inner.strong.compare_and_swap(n, n + 1, SeqCst);
391 if old == n { return Some(Arc { _ptr: self._ptr }) }
396 fn inner(&self) -> &ArcInner<T> {
397 // See comments above for why this is "safe"
398 unsafe { &**self._ptr }
402 #[unstable(feature = "alloc",
403 reason = "Weak pointers may not belong in this module.")]
404 impl<T: Sync + Send> Clone for Weak<T> {
405 /// Makes a clone of the `Weak<T>`.
407 /// This increases the weak reference count.
412 /// use std::sync::Arc;
414 /// let weak_five = Arc::new(5).downgrade();
416 /// weak_five.clone();
419 fn clone(&self) -> Weak<T> {
420 // See comments in Arc::clone() for why this is relaxed
421 self.inner().weak.fetch_add(1, Relaxed);
422 Weak { _ptr: self._ptr }
427 #[stable(feature = "rust1", since = "1.0.0")]
428 impl<T: Sync + Send> Drop for Weak<T> {
429 /// Drops the `Weak<T>`.
431 /// This will decrement the weak reference count.
436 /// use std::sync::Arc;
439 /// let five = Arc::new(5);
440 /// let weak_five = five.downgrade();
444 /// drop(weak_five); // explicit drop
447 /// let five = Arc::new(5);
448 /// let weak_five = five.downgrade();
452 /// } // implicit drop
455 let ptr = *self._ptr;
457 // see comments above for why this check is here
458 if ptr.is_null() { return }
460 // If we find out that we were the last weak pointer, then its time to deallocate the data
461 // entirely. See the discussion in Arc::drop() about the memory orderings
462 if self.inner().weak.fetch_sub(1, Release) == 1 {
463 atomic::fence(Acquire);
464 unsafe { deallocate(ptr as *mut u8, size_of::<ArcInner<T>>(),
465 min_align_of::<ArcInner<T>>()) }
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<T: PartialEq> PartialEq for Arc<T> {
472 /// Equality for two `Arc<T>`s.
474 /// Two `Arc<T>`s are equal if their inner value are equal.
479 /// use std::sync::Arc;
481 /// let five = Arc::new(5);
483 /// five == Arc::new(5);
485 fn eq(&self, other: &Arc<T>) -> bool { *(*self) == *(*other) }
487 /// Inequality for two `Arc<T>`s.
489 /// Two `Arc<T>`s are unequal if their inner value are unequal.
494 /// use std::sync::Arc;
496 /// let five = Arc::new(5);
498 /// five != Arc::new(5);
500 fn ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) }
502 #[stable(feature = "rust1", since = "1.0.0")]
503 impl<T: PartialOrd> PartialOrd for Arc<T> {
504 /// Partial comparison for two `Arc<T>`s.
506 /// The two are compared by calling `partial_cmp()` on their inner values.
511 /// use std::sync::Arc;
513 /// let five = Arc::new(5);
515 /// five.partial_cmp(&Arc::new(5));
517 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
518 (**self).partial_cmp(&**other)
521 /// Less-than comparison for two `Arc<T>`s.
523 /// The two are compared by calling `<` on their inner values.
528 /// use std::sync::Arc;
530 /// let five = Arc::new(5);
532 /// five < Arc::new(5);
534 fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) }
536 /// 'Less-than or equal to' comparison for two `Arc<T>`s.
538 /// The two are compared by calling `<=` on their inner values.
543 /// use std::sync::Arc;
545 /// let five = Arc::new(5);
547 /// five <= Arc::new(5);
549 fn le(&self, other: &Arc<T>) -> bool { *(*self) <= *(*other) }
551 /// Greater-than comparison for two `Arc<T>`s.
553 /// The two are compared by calling `>` on their inner values.
558 /// use std::sync::Arc;
560 /// let five = Arc::new(5);
562 /// five > Arc::new(5);
564 fn gt(&self, other: &Arc<T>) -> bool { *(*self) > *(*other) }
566 /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
568 /// The two are compared by calling `>=` on their inner values.
573 /// use std::sync::Arc;
575 /// let five = Arc::new(5);
577 /// five >= Arc::new(5);
579 fn ge(&self, other: &Arc<T>) -> bool { *(*self) >= *(*other) }
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl<T: Ord> Ord for Arc<T> {
583 fn cmp(&self, other: &Arc<T>) -> Ordering { (**self).cmp(&**other) }
585 #[stable(feature = "rust1", since = "1.0.0")]
586 impl<T: Eq> Eq for Arc<T> {}
588 #[stable(feature = "rust1", since = "1.0.0")]
589 impl<T: fmt::Display> fmt::Display for Arc<T> {
590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
591 fmt::Display::fmt(&**self, f)
595 #[stable(feature = "rust1", since = "1.0.0")]
596 impl<T: fmt::Debug> fmt::Debug for Arc<T> {
597 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
598 fmt::Debug::fmt(&**self, f)
602 #[stable(feature = "rust1", since = "1.0.0")]
603 impl<T: Default + Sync + Send> Default for Arc<T> {
604 #[stable(feature = "rust1", since = "1.0.0")]
605 fn default() -> Arc<T> { Arc::new(Default::default()) }
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl<T: Hash> Hash for Arc<T> {
610 fn hash<H: Hasher>(&self, state: &mut H) {
617 use std::clone::Clone;
618 use std::sync::mpsc::channel;
621 use std::option::Option;
622 use std::option::Option::{Some, None};
623 use std::sync::atomic;
624 use std::sync::atomic::Ordering::{Acquire, SeqCst};
627 use super::{Arc, Weak, weak_count, strong_count};
628 use std::sync::Mutex;
630 struct Canary(*mut atomic::AtomicUsize);
638 (*c).fetch_add(1, SeqCst);
646 fn manually_share_arc() {
647 let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
648 let arc_v = Arc::new(v);
650 let (tx, rx) = channel();
652 let _t = thread::spawn(move || {
653 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
654 assert_eq!((*arc_v)[3], 4);
657 tx.send(arc_v.clone()).unwrap();
659 assert_eq!((*arc_v)[2], 3);
660 assert_eq!((*arc_v)[4], 5);
664 fn test_cowarc_clone_make_unique() {
665 let mut cow0 = Arc::new(75);
666 let mut cow1 = cow0.clone();
667 let mut cow2 = cow1.clone();
669 assert!(75 == *cow0.make_unique());
670 assert!(75 == *cow1.make_unique());
671 assert!(75 == *cow2.make_unique());
673 *cow0.make_unique() += 1;
674 *cow1.make_unique() += 2;
675 *cow2.make_unique() += 3;
677 assert!(76 == *cow0);
678 assert!(77 == *cow1);
679 assert!(78 == *cow2);
681 // none should point to the same backing memory
682 assert!(*cow0 != *cow1);
683 assert!(*cow0 != *cow2);
684 assert!(*cow1 != *cow2);
688 fn test_cowarc_clone_unique2() {
689 let mut cow0 = Arc::new(75);
690 let cow1 = cow0.clone();
691 let cow2 = cow1.clone();
693 assert!(75 == *cow0);
694 assert!(75 == *cow1);
695 assert!(75 == *cow2);
697 *cow0.make_unique() += 1;
699 assert!(76 == *cow0);
700 assert!(75 == *cow1);
701 assert!(75 == *cow2);
703 // cow1 and cow2 should share the same contents
704 // cow0 should have a unique reference
705 assert!(*cow0 != *cow1);
706 assert!(*cow0 != *cow2);
707 assert!(*cow1 == *cow2);
711 fn test_cowarc_clone_weak() {
712 let mut cow0 = Arc::new(75);
713 let cow1_weak = cow0.downgrade();
715 assert!(75 == *cow0);
716 assert!(75 == *cow1_weak.upgrade().unwrap());
718 *cow0.make_unique() += 1;
720 assert!(76 == *cow0);
721 assert!(cow1_weak.upgrade().is_none());
727 let y = x.downgrade();
728 assert!(y.upgrade().is_some());
734 let y = x.downgrade();
736 assert!(y.upgrade().is_none());
740 fn weak_self_cyclic() {
742 x: Mutex<Option<Weak<Cycle>>>
745 let a = Arc::new(Cycle { x: Mutex::new(None) });
746 let b = a.clone().downgrade();
747 *a.x.lock().unwrap() = Some(b);
749 // hopefully we don't double-free (or leak)...
754 let mut canary = atomic::AtomicUsize::new(0);
755 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
757 assert!(canary.load(Acquire) == 1);
762 let mut canary = atomic::AtomicUsize::new(0);
763 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
764 let arc_weak = arc.downgrade();
765 assert!(canary.load(Acquire) == 0);
767 assert!(canary.load(Acquire) == 1);
772 fn test_strong_count() {
773 let a = Arc::new(0u32);
774 assert!(strong_count(&a) == 1);
775 let w = a.downgrade();
776 assert!(strong_count(&a) == 1);
777 let b = w.upgrade().expect("");
778 assert!(strong_count(&b) == 2);
779 assert!(strong_count(&a) == 2);
782 assert!(strong_count(&b) == 1);
784 assert!(strong_count(&b) == 2);
785 assert!(strong_count(&c) == 2);
789 fn test_weak_count() {
790 let a = Arc::new(0u32);
791 assert!(strong_count(&a) == 1);
792 assert!(weak_count(&a) == 0);
793 let w = a.downgrade();
794 assert!(strong_count(&a) == 1);
795 assert!(weak_count(&a) == 1);
797 assert!(weak_count(&a) == 2);
800 assert!(strong_count(&a) == 1);
801 assert!(weak_count(&a) == 0);
803 assert!(strong_count(&a) == 2);
804 assert!(weak_count(&a) == 0);
805 let d = c.downgrade();
806 assert!(weak_count(&c) == 1);
807 assert!(strong_count(&c) == 2);
816 let a = Arc::new(5u32);
817 assert_eq!(format!("{:?}", a), "5");
820 // Make sure deriving works with Arc<T>
821 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
822 struct Foo { inner: Arc<i32> }