]> git.lizzy.rs Git - rust.git/blob - src/liballoc/arc.rs
rollup merge of #20642: michaelwoerister/sane-source-locations-pt1
[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;
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 #[stable]
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)
585     }
586 }
587
588 #[stable]
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)
592     }
593 }
594
595 #[stable]
596 impl<T: Default + Sync + Send> Default for Arc<T> {
597     #[stable]
598     fn default() -> Arc<T> { Arc::new(Default::default()) }
599 }
600
601 impl<H: Hasher, T: Hash<H>> Hash<H> for Arc<T> {
602     fn hash(&self, state: &mut H) {
603         (**self).hash(state)
604     }
605 }
606
607 #[cfg(test)]
608 #[allow(unstable)]
609 mod tests {
610     use std::clone::Clone;
611     use std::sync::mpsc::channel;
612     use std::mem::drop;
613     use std::ops::Drop;
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;
619     use std::vec::Vec;
620     use super::{Arc, Weak, weak_count, strong_count};
621     use std::sync::Mutex;
622
623     struct Canary(*mut atomic::AtomicUsize);
624
625     impl Drop for Canary
626     {
627         fn drop(&mut self) {
628             unsafe {
629                 match *self {
630                     Canary(c) => {
631                         (*c).fetch_add(1, SeqCst);
632                     }
633                 }
634             }
635         }
636     }
637
638     #[test]
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);
642
643         let (tx, rx) = channel();
644
645         let _t = Thread::spawn(move || {
646             let arc_v: Arc<Vec<int>> = rx.recv().unwrap();
647             assert_eq!((*arc_v)[3], 4);
648         });
649
650         tx.send(arc_v.clone()).unwrap();
651
652         assert_eq!((*arc_v)[2], 3);
653         assert_eq!((*arc_v)[4], 5);
654     }
655
656     #[test]
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();
661
662         assert!(75 == *cow0.make_unique());
663         assert!(75 == *cow1.make_unique());
664         assert!(75 == *cow2.make_unique());
665
666         *cow0.make_unique() += 1;
667         *cow1.make_unique() += 2;
668         *cow2.make_unique() += 3;
669
670         assert!(76 == *cow0);
671         assert!(77 == *cow1);
672         assert!(78 == *cow2);
673
674         // none should point to the same backing memory
675         assert!(*cow0 != *cow1);
676         assert!(*cow0 != *cow2);
677         assert!(*cow1 != *cow2);
678     }
679
680     #[test]
681     fn test_cowarc_clone_unique2() {
682         let mut cow0 = Arc::new(75u);
683         let cow1 = cow0.clone();
684         let cow2 = cow1.clone();
685
686         assert!(75 == *cow0);
687         assert!(75 == *cow1);
688         assert!(75 == *cow2);
689
690         *cow0.make_unique() += 1;
691
692         assert!(76 == *cow0);
693         assert!(75 == *cow1);
694         assert!(75 == *cow2);
695
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);
701     }
702
703     #[test]
704     fn test_cowarc_clone_weak() {
705         let mut cow0 = Arc::new(75u);
706         let cow1_weak = cow0.downgrade();
707
708         assert!(75 == *cow0);
709         assert!(75 == *cow1_weak.upgrade().unwrap());
710
711         *cow0.make_unique() += 1;
712
713         assert!(76 == *cow0);
714         assert!(cow1_weak.upgrade().is_none());
715     }
716
717     #[test]
718     fn test_live() {
719         let x = Arc::new(5i);
720         let y = x.downgrade();
721         assert!(y.upgrade().is_some());
722     }
723
724     #[test]
725     fn test_dead() {
726         let x = Arc::new(5i);
727         let y = x.downgrade();
728         drop(x);
729         assert!(y.upgrade().is_none());
730     }
731
732     #[test]
733     fn weak_self_cyclic() {
734         struct Cycle {
735             x: Mutex<Option<Weak<Cycle>>>
736         }
737
738         let a = Arc::new(Cycle { x: Mutex::new(None) });
739         let b = a.clone().downgrade();
740         *a.x.lock().unwrap() = Some(b);
741
742         // hopefully we don't double-free (or leak)...
743     }
744
745     #[test]
746     fn drop_arc() {
747         let mut canary = atomic::AtomicUsize::new(0);
748         let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
749         drop(x);
750         assert!(canary.load(Acquire) == 1);
751     }
752
753     #[test]
754     fn drop_arc_weak() {
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);
759         drop(arc);
760         assert!(canary.load(Acquire) == 1);
761         drop(arc_weak);
762     }
763
764     #[test]
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);
773         drop(w);
774         drop(a);
775         assert!(strong_count(&b) == 1);
776         let c = b.clone();
777         assert!(strong_count(&b) == 2);
778         assert!(strong_count(&c) == 2);
779     }
780
781     #[test]
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);
789         let x = w.clone();
790         assert!(weak_count(&a) == 2);
791         drop(w);
792         drop(x);
793         assert!(strong_count(&a) == 1);
794         assert!(weak_count(&a) == 0);
795         let c = a.clone();
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);
801
802         drop(a);
803         drop(c);
804         drop(d);
805     }
806
807     #[test]
808     fn show_arc() {
809         let a = Arc::new(5u32);
810         assert_eq!(format!("{:?}", a), "5");
811     }
812
813     // Make sure deriving works with Arc<T>
814     #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Show, Default)]
815     struct Foo { inner: Arc<int> }
816 }