]> git.lizzy.rs Git - rust.git/blob - src/liballoc/arc.rs
debuginfo: Make debuginfo source location assignment more stable (Pt. 1)
[rust.git] / src / liballoc / arc.rs
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.
4 //
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.
10
11 #![stable]
12
13 //! Threadsafe reference-counted boxes (the `Arc<T>` type).
14 //!
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.
18 //!
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.
22 //!
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.
26 //!
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.
29 //!
30 //! # Examples
31 //!
32 //! Sharing some immutable data between tasks:
33 //!
34 //! ```
35 //! use std::sync::Arc;
36 //! use std::thread::Thread;
37 //!
38 //! let five = Arc::new(5i);
39 //!
40 //! for _ in range(0u, 10) {
41 //!     let five = five.clone();
42 //!
43 //!     Thread::spawn(move || {
44 //!         println!("{:?}", five);
45 //!     });
46 //! }
47 //! ```
48 //!
49 //! Sharing mutable data safely between tasks with a `Mutex`:
50 //!
51 //! ```
52 //! use std::sync::{Arc, Mutex};
53 //! use std::thread::Thread;
54 //!
55 //! let five = Arc::new(Mutex::new(5i));
56 //!
57 //! for _ in range(0u, 10) {
58 //!     let five = five.clone();
59 //!
60 //!     Thread::spawn(move || {
61 //!         let mut number = five.lock().unwrap();
62 //!
63 //!         *number += 1;
64 //!
65 //!         println!("{}", *number); // prints 6
66 //!     });
67 //! }
68 //! ```
69
70 use core::prelude::*;
71
72 use core::atomic;
73 use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
74 use core::borrow::BorrowFrom;
75 use core::fmt::{self, Show};
76 use core::cmp::{Ordering};
77 use core::default::Default;
78 use core::mem::{min_align_of, size_of};
79 use core::mem;
80 use core::nonzero::NonZero;
81 use core::ops::Deref;
82 use core::ptr;
83 use core::hash::{Hash, Hasher};
84 use heap::deallocate;
85
86 /// An atomically reference counted wrapper for shared state.
87 ///
88 /// # Example
89 ///
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.
92 ///
93 /// ```rust
94 /// use std::sync::Arc;
95 /// use std::thread::Thread;
96 ///
97 /// fn main() {
98 ///     let numbers: Vec<_> = range(0, 100u32).map(|i| i as f32).collect();
99 ///     let shared_numbers = Arc::new(numbers);
100 ///
101 ///     for _ in range(0u, 10) {
102 ///         let child_numbers = shared_numbers.clone();
103 ///
104 ///         Thread::spawn(move || {
105 ///             let local_numbers = child_numbers.as_slice();
106 ///
107 ///             // Work with the local numbers
108 ///         });
109 ///     }
110 /// }
111 /// ```
112 #[unsafe_no_drop_flag]
113 #[stable]
114 pub struct Arc<T> {
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>>,
118 }
119
120 unsafe impl<T: Sync + Send> Send for Arc<T> { }
121 unsafe impl<T: Sync + Send> Sync for Arc<T> { }
122
123
124 /// A weak pointer to an `Arc`.
125 ///
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."]
130 pub struct Weak<T> {
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>>,
134 }
135
136 unsafe impl<T: Sync + Send> Send for Weak<T> { }
137 unsafe impl<T: Sync + Send> Sync for Weak<T> { }
138
139 struct ArcInner<T> {
140     strong: atomic::AtomicUsize,
141     weak: atomic::AtomicUsize,
142     data: T,
143 }
144
145 unsafe impl<T: Sync + Send> Send for ArcInner<T> {}
146 unsafe impl<T: Sync + Send> Sync for ArcInner<T> {}
147
148 impl<T> Arc<T> {
149     /// Constructs a new `Arc<T>`.
150     ///
151     /// # Examples
152     ///
153     /// ```
154     /// use std::sync::Arc;
155     ///
156     /// let five = Arc::new(5i);
157     /// ```
158     #[inline]
159     #[stable]
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),
166             data: data,
167         };
168         Arc { _ptr: unsafe { NonZero::new(mem::transmute(x)) } }
169     }
170
171     /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
172     ///
173     /// # Examples
174     ///
175     /// ```
176     /// use std::sync::Arc;
177     ///
178     /// let five = Arc::new(5i);
179     ///
180     /// let weak_five = five.downgrade();
181     /// ```
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 }
187     }
188 }
189
190 impl<T> Arc<T> {
191     #[inline]
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 }
198     }
199 }
200
201 /// Get the number of weak references to this value.
202 #[inline]
203 #[unstable]
204 pub fn weak_count<T>(this: &Arc<T>) -> uint { this.inner().weak.load(SeqCst) - 1 }
205
206 /// Get the number of strong references to this value.
207 #[inline]
208 #[unstable]
209 pub fn strong_count<T>(this: &Arc<T>) -> uint { this.inner().strong.load(SeqCst) }
210
211 #[stable]
212 impl<T> Clone for Arc<T> {
213     /// Makes a clone of the `Arc<T>`.
214     ///
215     /// This increases the strong reference count.
216     ///
217     /// # Examples
218     ///
219     /// ```
220     /// use std::sync::Arc;
221     ///
222     /// let five = Arc::new(5i);
223     ///
224     /// five.clone();
225     /// ```
226     #[inline]
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.
230         //
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.
235         //
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 }
239     }
240 }
241
242 impl<T> BorrowFrom<Arc<T>> for T {
243     fn borrow_from(owned: &Arc<T>) -> &T {
244         &**owned
245     }
246 }
247
248 #[stable]
249 impl<T> Deref for Arc<T> {
250     type Target = T;
251
252     #[inline]
253     fn deref(&self) -> &T {
254         &self.inner().data
255     }
256 }
257
258 impl<T: Send + Sync + Clone> Arc<T> {
259     /// Make a mutable reference from the given `Arc<T>`.
260     ///
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.
263     ///
264     /// # Examples
265     ///
266     /// ```
267     /// use std::sync::Arc;
268     ///
269     /// let mut five = Arc::new(5i);
270     ///
271     /// let mut_five = five.make_unique();
272     /// ```
273     #[inline]
274     #[unstable]
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())
281         }
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 };
287         &mut inner.data
288     }
289 }
290
291 #[unsafe_destructor]
292 #[stable]
293 impl<T: Sync + Send> Drop for Arc<T> {
294     /// Drops the `Arc<T>`.
295     ///
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.
298     ///
299     /// # Examples
300     ///
301     /// ```
302     /// use std::sync::Arc;
303     ///
304     /// {
305     ///     let five = Arc::new(5i);
306     ///
307     ///     // stuff
308     ///
309     ///     drop(five); // explict drop
310     /// }
311     /// {
312     ///     let five = Arc::new(5i);
313     ///
314     ///     // stuff
315     ///
316     /// } // implicit drop
317     /// ```
318     fn drop(&mut self) {
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 }
323
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 }
328
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
333         // the data.
334         //
335         // As explained in the [Boost documentation][1],
336         //
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.
342         //
343         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
344         atomic::fence(Acquire);
345
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)); }
349
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>>()) }
354         }
355     }
356 }
357
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.
361     ///
362     /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
363     ///
364     /// Returns `None` if there were no strong references and the data was destroyed.
365     ///
366     /// # Examples
367     ///
368     /// ```
369     /// use std::sync::Arc;
370     ///
371     /// let five = Arc::new(5i);
372     ///
373     /// let weak_five = five.downgrade();
374     ///
375     /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
376     /// ```
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();
381         loop {
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 }) }
386         }
387     }
388
389     #[inline]
390     fn inner(&self) -> &ArcInner<T> {
391         // See comments above for why this is "safe"
392         unsafe { &**self._ptr }
393     }
394 }
395
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>`.
399     ///
400     /// This increases the weak reference count.
401     ///
402     /// # Examples
403     ///
404     /// ```
405     /// use std::sync::Arc;
406     ///
407     /// let weak_five = Arc::new(5i).downgrade();
408     ///
409     /// weak_five.clone();
410     /// ```
411     #[inline]
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 }
416     }
417 }
418
419 #[unsafe_destructor]
420 #[stable]
421 impl<T: Sync + Send> Drop for Weak<T> {
422     /// Drops the `Weak<T>`.
423     ///
424     /// This will decrement the weak reference count.
425     ///
426     /// # Examples
427     ///
428     /// ```
429     /// use std::sync::Arc;
430     ///
431     /// {
432     ///     let five = Arc::new(5i);
433     ///     let weak_five = five.downgrade();
434     ///
435     ///     // stuff
436     ///
437     ///     drop(weak_five); // explict drop
438     /// }
439     /// {
440     ///     let five = Arc::new(5i);
441     ///     let weak_five = five.downgrade();
442     ///
443     ///     // stuff
444     ///
445     /// } // implicit drop
446     /// ```
447     fn drop(&mut self) {
448         let ptr = *self._ptr;
449
450         // see comments above for why this check is here
451         if ptr.is_null() { return }
452
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>>()) }
459         }
460     }
461 }
462
463 #[stable]
464 impl<T: PartialEq> PartialEq for Arc<T> {
465     /// Equality for two `Arc<T>`s.
466     ///
467     /// Two `Arc<T>`s are equal if their inner value are equal.
468     ///
469     /// # Examples
470     ///
471     /// ```
472     /// use std::sync::Arc;
473     ///
474     /// let five = Arc::new(5i);
475     ///
476     /// five == Arc::new(5i);
477     /// ```
478     fn eq(&self, other: &Arc<T>) -> bool { *(*self) == *(*other) }
479
480     /// Inequality for two `Arc<T>`s.
481     ///
482     /// Two `Arc<T>`s are unequal if their inner value are unequal.
483     ///
484     /// # Examples
485     ///
486     /// ```
487     /// use std::sync::Arc;
488     ///
489     /// let five = Arc::new(5i);
490     ///
491     /// five != Arc::new(5i);
492     /// ```
493     fn ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) }
494 }
495 #[stable]
496 impl<T: PartialOrd> PartialOrd for Arc<T> {
497     /// Partial comparison for two `Arc<T>`s.
498     ///
499     /// The two are compared by calling `partial_cmp()` on their inner values.
500     ///
501     /// # Examples
502     ///
503     /// ```
504     /// use std::sync::Arc;
505     ///
506     /// let five = Arc::new(5i);
507     ///
508     /// five.partial_cmp(&Arc::new(5i));
509     /// ```
510     fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
511         (**self).partial_cmp(&**other)
512     }
513
514     /// Less-than comparison for two `Arc<T>`s.
515     ///
516     /// The two are compared by calling `<` on their inner values.
517     ///
518     /// # Examples
519     ///
520     /// ```
521     /// use std::sync::Arc;
522     ///
523     /// let five = Arc::new(5i);
524     ///
525     /// five < Arc::new(5i);
526     /// ```
527     fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) }
528
529     /// 'Less-than or equal to' comparison for two `Arc<T>`s.
530     ///
531     /// The two are compared by calling `<=` on their inner values.
532     ///
533     /// # Examples
534     ///
535     /// ```
536     /// use std::sync::Arc;
537     ///
538     /// let five = Arc::new(5i);
539     ///
540     /// five <= Arc::new(5i);
541     /// ```
542     fn le(&self, other: &Arc<T>) -> bool { *(*self) <= *(*other) }
543
544     /// Greater-than comparison for two `Arc<T>`s.
545     ///
546     /// The two are compared by calling `>` on their inner values.
547     ///
548     /// # Examples
549     ///
550     /// ```
551     /// use std::sync::Arc;
552     ///
553     /// let five = Arc::new(5i);
554     ///
555     /// five > Arc::new(5i);
556     /// ```
557     fn gt(&self, other: &Arc<T>) -> bool { *(*self) > *(*other) }
558
559     /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
560     ///
561     /// The two are compared by calling `>=` on their inner values.
562     ///
563     /// # Examples
564     ///
565     /// ```
566     /// use std::sync::Arc;
567     ///
568     /// let five = Arc::new(5i);
569     ///
570     /// five >= Arc::new(5i);
571     /// ```
572     fn ge(&self, other: &Arc<T>) -> bool { *(*self) >= *(*other) }
573 }
574 #[stable]
575 impl<T: Ord> Ord for Arc<T> {
576     fn cmp(&self, other: &Arc<T>) -> Ordering { (**self).cmp(&**other) }
577 }
578 #[stable]
579 impl<T: Eq> Eq for Arc<T> {}
580
581 impl<T: fmt::Show> fmt::Show for Arc<T> {
582     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
583         write!(f, "Arc({:?})", (**self))
584     }
585 }
586
587 #[stable]
588 impl<T: fmt::String> fmt::String for Arc<T> {
589     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
590         fmt::String::fmt(&**self, f)
591     }
592 }
593
594 #[stable]
595 impl<T: Default + Sync + Send> Default for Arc<T> {
596     #[stable]
597     fn default() -> Arc<T> { Arc::new(Default::default()) }
598 }
599
600 impl<H: Hasher, T: Hash<H>> Hash<H> for Arc<T> {
601     fn hash(&self, state: &mut H) {
602         (**self).hash(state)
603     }
604 }
605
606 #[cfg(test)]
607 #[allow(unstable)]
608 mod tests {
609     use std::clone::Clone;
610     use std::sync::mpsc::channel;
611     use std::mem::drop;
612     use std::ops::Drop;
613     use std::option::Option;
614     use std::option::Option::{Some, None};
615     use std::sync::atomic;
616     use std::sync::atomic::Ordering::{Acquire, SeqCst};
617     use std::thread::Thread;
618     use std::vec::Vec;
619     use super::{Arc, Weak, weak_count, strong_count};
620     use std::sync::Mutex;
621
622     struct Canary(*mut atomic::AtomicUsize);
623
624     impl Drop for Canary
625     {
626         fn drop(&mut self) {
627             unsafe {
628                 match *self {
629                     Canary(c) => {
630                         (*c).fetch_add(1, SeqCst);
631                     }
632                 }
633             }
634         }
635     }
636
637     #[test]
638     fn manually_share_arc() {
639         let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
640         let arc_v = Arc::new(v);
641
642         let (tx, rx) = channel();
643
644         let _t = Thread::spawn(move || {
645             let arc_v: Arc<Vec<int>> = rx.recv().unwrap();
646             assert_eq!((*arc_v)[3], 4);
647         });
648
649         tx.send(arc_v.clone()).unwrap();
650
651         assert_eq!((*arc_v)[2], 3);
652         assert_eq!((*arc_v)[4], 5);
653     }
654
655     #[test]
656     fn test_cowarc_clone_make_unique() {
657         let mut cow0 = Arc::new(75u);
658         let mut cow1 = cow0.clone();
659         let mut cow2 = cow1.clone();
660
661         assert!(75 == *cow0.make_unique());
662         assert!(75 == *cow1.make_unique());
663         assert!(75 == *cow2.make_unique());
664
665         *cow0.make_unique() += 1;
666         *cow1.make_unique() += 2;
667         *cow2.make_unique() += 3;
668
669         assert!(76 == *cow0);
670         assert!(77 == *cow1);
671         assert!(78 == *cow2);
672
673         // none should point to the same backing memory
674         assert!(*cow0 != *cow1);
675         assert!(*cow0 != *cow2);
676         assert!(*cow1 != *cow2);
677     }
678
679     #[test]
680     fn test_cowarc_clone_unique2() {
681         let mut cow0 = Arc::new(75u);
682         let cow1 = cow0.clone();
683         let cow2 = cow1.clone();
684
685         assert!(75 == *cow0);
686         assert!(75 == *cow1);
687         assert!(75 == *cow2);
688
689         *cow0.make_unique() += 1;
690
691         assert!(76 == *cow0);
692         assert!(75 == *cow1);
693         assert!(75 == *cow2);
694
695         // cow1 and cow2 should share the same contents
696         // cow0 should have a unique reference
697         assert!(*cow0 != *cow1);
698         assert!(*cow0 != *cow2);
699         assert!(*cow1 == *cow2);
700     }
701
702     #[test]
703     fn test_cowarc_clone_weak() {
704         let mut cow0 = Arc::new(75u);
705         let cow1_weak = cow0.downgrade();
706
707         assert!(75 == *cow0);
708         assert!(75 == *cow1_weak.upgrade().unwrap());
709
710         *cow0.make_unique() += 1;
711
712         assert!(76 == *cow0);
713         assert!(cow1_weak.upgrade().is_none());
714     }
715
716     #[test]
717     fn test_live() {
718         let x = Arc::new(5i);
719         let y = x.downgrade();
720         assert!(y.upgrade().is_some());
721     }
722
723     #[test]
724     fn test_dead() {
725         let x = Arc::new(5i);
726         let y = x.downgrade();
727         drop(x);
728         assert!(y.upgrade().is_none());
729     }
730
731     #[test]
732     fn weak_self_cyclic() {
733         struct Cycle {
734             x: Mutex<Option<Weak<Cycle>>>
735         }
736
737         let a = Arc::new(Cycle { x: Mutex::new(None) });
738         let b = a.clone().downgrade();
739         *a.x.lock().unwrap() = Some(b);
740
741         // hopefully we don't double-free (or leak)...
742     }
743
744     #[test]
745     fn drop_arc() {
746         let mut canary = atomic::AtomicUsize::new(0);
747         let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
748         drop(x);
749         assert!(canary.load(Acquire) == 1);
750     }
751
752     #[test]
753     fn drop_arc_weak() {
754         let mut canary = atomic::AtomicUsize::new(0);
755         let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
756         let arc_weak = arc.downgrade();
757         assert!(canary.load(Acquire) == 0);
758         drop(arc);
759         assert!(canary.load(Acquire) == 1);
760         drop(arc_weak);
761     }
762
763     #[test]
764     fn test_strong_count() {
765         let a = Arc::new(0u32);
766         assert!(strong_count(&a) == 1);
767         let w = a.downgrade();
768         assert!(strong_count(&a) == 1);
769         let b = w.upgrade().expect("");
770         assert!(strong_count(&b) == 2);
771         assert!(strong_count(&a) == 2);
772         drop(w);
773         drop(a);
774         assert!(strong_count(&b) == 1);
775         let c = b.clone();
776         assert!(strong_count(&b) == 2);
777         assert!(strong_count(&c) == 2);
778     }
779
780     #[test]
781     fn test_weak_count() {
782         let a = Arc::new(0u32);
783         assert!(strong_count(&a) == 1);
784         assert!(weak_count(&a) == 0);
785         let w = a.downgrade();
786         assert!(strong_count(&a) == 1);
787         assert!(weak_count(&a) == 1);
788         let x = w.clone();
789         assert!(weak_count(&a) == 2);
790         drop(w);
791         drop(x);
792         assert!(strong_count(&a) == 1);
793         assert!(weak_count(&a) == 0);
794         let c = a.clone();
795         assert!(strong_count(&a) == 2);
796         assert!(weak_count(&a) == 0);
797         let d = c.downgrade();
798         assert!(weak_count(&c) == 1);
799         assert!(strong_count(&c) == 2);
800
801         drop(a);
802         drop(c);
803         drop(d);
804     }
805
806     #[test]
807     fn show_arc() {
808         let a = Arc::new(5u32);
809         assert!(format!("{:?}", a) == "Arc(5u32)")
810     }
811
812     // Make sure deriving works with Arc<T>
813     #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Show, Default)]
814     struct Foo { inner: Arc<int> }
815 }