mutex.rs 22.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

F
Flavio Percoco 已提交
11
use cell::UnsafeCell;
12
use fmt;
13
use mem;
14
use ops::{Deref, DerefMut};
15
use ptr;
A
Alex Crichton 已提交
16
use sys_common::mutex as sys;
17
use sys_common::poison::{self, TryLockError, TryLockResult, LockResult};
18 19 20

/// A mutual exclusion primitive useful for protecting shared data
///
A
Alex Crichton 已提交
21
/// This mutex will block threads waiting for the lock to become available. The
G
Guillaume Gomez 已提交
22
/// mutex can also be statically initialized or created via a [`new`]
A
Alex Crichton 已提交
23 24
/// constructor. Each mutex has a type parameter which represents the data that
/// it is protecting. The data can only be accessed through the RAII guards
G
Guillaume Gomez 已提交
25
/// returned from [`lock`] and [`try_lock`], which guarantees that the data is only
A
Alex Crichton 已提交
26 27 28 29
/// ever accessed when the mutex is locked.
///
/// # Poisoning
///
30 31
/// The mutexes in this module implement a strategy called "poisoning" where a
/// mutex is considered poisoned whenever a thread panics while holding the
G
Guillaume Gomez 已提交
32
/// mutex. Once a mutex is poisoned, all other threads are unable to access the
33 34
/// data by default as it is likely tainted (some invariant is not being
/// upheld).
35
///
G
Guillaume Gomez 已提交
36 37 38
/// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a
/// [`Result`] which indicates whether a mutex has been poisoned or not. Most
/// usage of a mutex will simply [`unwrap()`] these results, propagating panics
39 40 41
/// among threads to ensure that a possibly invalid invariant is not witnessed.
///
/// A poisoned mutex, however, does not prevent all access to the underlying
G
Guillaume Gomez 已提交
42
/// data. The [`PoisonError`] type has an [`into_inner`] method which will return
43 44 45
/// the guard that would have otherwise been returned on a successful lock. This
/// allows access to the data, despite the lock being poisoned.
///
G
Guillaume Gomez 已提交
46 47 48 49 50 51 52 53
/// [`new`]: #method.new
/// [`lock`]: #method.lock
/// [`try_lock`]: #method.try_lock
/// [`Result`]: ../../std/result/enum.Result.html
/// [`unwrap()`]: ../../std/result/enum.Result.html#method.unwrap
/// [`PoisonError`]: ../../std/sync/struct.PoisonError.html
/// [`into_inner`]: ../../std/sync/struct.PoisonError.html#method.into_inner
///
54
/// # Examples
55
///
56
/// ```
A
Alex Crichton 已提交
57
/// use std::sync::{Arc, Mutex};
A
Aaron Turon 已提交
58
/// use std::thread;
59
/// use std::sync::mpsc::channel;
60
///
N
Nick Cameron 已提交
61
/// const N: usize = 10;
62
///
A
Alex Crichton 已提交
63 64 65
/// // Spawn a few threads to increment a shared variable (non-atomically), and
/// // let the main thread know once all increments are done.
/// //
66
/// // Here we're using an Arc to share memory among threads, and the data inside
A
Alex Crichton 已提交
67 68 69 70
/// // the Arc is protected with a mutex.
/// let data = Arc::new(Mutex::new(0));
///
/// let (tx, rx) = channel();
G
Geoffry Song 已提交
71
/// for _ in 0..N {
A
Alex Crichton 已提交
72
///     let (data, tx) = (data.clone(), tx.clone());
A
Aaron Turon 已提交
73
///     thread::spawn(move || {
74
///         // The shared state can only be accessed once the lock is held.
A
Alex Crichton 已提交
75 76
///         // Our non-atomic increment is safe because we're the only thread
///         // which can access the shared state when the lock is held.
77 78
///         //
///         // We unwrap() the return value to assert that we are not expecting
79
///         // threads to ever fail while holding the lock.
80
///         let mut data = data.lock().unwrap();
A
Alex Crichton 已提交
81 82
///         *data += 1;
///         if *data == N {
83
///             tx.send(()).unwrap();
A
Alex Crichton 已提交
84 85
///         }
///         // the lock is unlocked here when `data` goes out of scope.
A
Aaron Turon 已提交
86
///     });
A
Alex Crichton 已提交
87 88
/// }
///
89
/// rx.recv().unwrap();
90
/// ```
91 92 93
///
/// To recover from a poisoned mutex:
///
94
/// ```
95
/// use std::sync::{Arc, Mutex};
A
Aaron Turon 已提交
96
/// use std::thread;
97
///
98
/// let lock = Arc::new(Mutex::new(0_u32));
99 100
/// let lock2 = lock.clone();
///
A
Aaron Turon 已提交
101
/// let _ = thread::spawn(move || -> () {
102 103
///     // This thread will acquire the mutex first, unwrapping the result of
///     // `lock` because the lock has not been poisoned.
104
///     let _guard = lock2.lock().unwrap();
105 106 107 108 109 110 111 112 113 114
///
///     // This panic while holding the lock (`_guard` is in scope) will poison
///     // the mutex.
///     panic!();
/// }).join();
///
/// // The lock is poisoned by this point, but the returned result can be
/// // pattern matched on to return the underlying guard on both branches.
/// let mut guard = match lock.lock() {
///     Ok(guard) => guard,
115
///     Err(poisoned) => poisoned.into_inner(),
116 117 118 119
/// };
///
/// *guard += 1;
/// ```
B
Brian Anderson 已提交
120
#[stable(feature = "rust1", since = "1.0.0")]
121
pub struct Mutex<T: ?Sized> {
A
Alex Crichton 已提交
122 123 124
    // Note that this mutex is in a *box*, not inlined into the struct itself.
    // Once a native mutex has been used once, its address can never change (it
    // can't be moved). This mutex type can be safely moved at any time, so to
G
Guillaume Gomez 已提交
125
    // ensure that the native mutex is used correctly we box the inner mutex to
A
Alex Crichton 已提交
126 127 128
    // give it a constant address.
    inner: Box<sys::Mutex>,
    poison: poison::Flag,
129
    data: UnsafeCell<T>,
130 131
}

132 133
// these are the only places where `T: Send` matters; all other
// functionality works fine on a single thread.
134
#[stable(feature = "rust1", since = "1.0.0")]
135
unsafe impl<T: ?Sized + Send> Send for Mutex<T> { }
136
#[stable(feature = "rust1", since = "1.0.0")]
137
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> { }
F
Flavio Percoco 已提交
138

139 140
/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
A
Alex Crichton 已提交
141
///
S
ScottAbbey 已提交
142
/// The data protected by the mutex can be accessed through this guard via its
143
/// [`Deref`] and [`DerefMut`] implementations.
144
///
145
/// This structure is created by the [`lock`] and [`try_lock`] methods on
146 147
/// [`Mutex`].
///
148 149
/// [`Deref`]: ../../std/ops/trait.Deref.html
/// [`DerefMut`]: ../../std/ops/trait.DerefMut.html
150 151
/// [`lock`]: struct.Mutex.html#method.lock
/// [`try_lock`]: struct.Mutex.html#method.try_lock
152
/// [`Mutex`]: struct.Mutex.html
153
#[must_use]
B
Brian Anderson 已提交
154
#[stable(feature = "rust1", since = "1.0.0")]
155
pub struct MutexGuard<'a, T: ?Sized + 'a> {
A
Alex Crichton 已提交
156 157
    // funny underscores due to how Deref/DerefMut currently work (they
    // disregard field privacy).
A
Alex Crichton 已提交
158
    __lock: &'a Mutex<T>,
159
    __poison: poison::Guard,
160 161
}

162
#[stable(feature = "rust1", since = "1.0.0")]
163
impl<'a, T: ?Sized> !Send for MutexGuard<'a, T> { }
164
#[stable(feature = "mutexguard", since = "1.19.0")]
165
unsafe impl<'a, T: ?Sized + Sync> Sync for MutexGuard<'a, T> { }
166

167
impl<T> Mutex<T> {
A
Alex Crichton 已提交
168
    /// Creates a new mutex in an unlocked state ready for use.
169 170 171 172 173 174 175 176
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Mutex;
    ///
    /// let mutex = Mutex::new(0);
    /// ```
B
Brian Anderson 已提交
177
    #[stable(feature = "rust1", since = "1.0.0")]
A
Alex Crichton 已提交
178
    pub fn new(t: T) -> Mutex<T> {
179
        let mut m = Mutex {
A
Alex Crichton 已提交
180 181
            inner: box sys::Mutex::new(),
            poison: poison::Flag::new(),
182
            data: UnsafeCell::new(t),
183 184
        };
        unsafe {
A
Alex Crichton 已提交
185
            m.inner.init();
A
Alex Crichton 已提交
186
        }
187
        m
A
Alex Crichton 已提交
188
    }
189
}
A
Alex Crichton 已提交
190

191
impl<T: ?Sized> Mutex<T> {
192
    /// Acquires a mutex, blocking the current thread until it is able to do so.
A
Alex Crichton 已提交
193
    ///
194
    /// This function will block the local thread until it is available to acquire
G
Guillaume Gomez 已提交
195
    /// the mutex. Upon returning, the thread is the only thread with the lock
A
Alex Crichton 已提交
196 197 198
    /// held. An RAII guard is returned to allow scoped unlock of the lock. When
    /// the guard goes out of scope, the mutex will be unlocked.
    ///
199
    /// The exact behavior on locking a mutex in the thread which already holds
200 201
    /// the lock is left unspecified. However, this function will not return on
    /// the second call (it might panic or deadlock, for example).
202
    ///
203
    /// # Errors
A
Alex Crichton 已提交
204 205
    ///
    /// If another user of this mutex panicked while holding the mutex, then
206
    /// this call will return an error once the mutex is acquired.
207 208 209 210 211
    ///
    /// # Panics
    ///
    /// This function might panic when called if the lock is already held by
    /// the current thread.
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::{Arc, Mutex};
    /// use std::thread;
    ///
    /// let mutex = Arc::new(Mutex::new(0));
    /// let c_mutex = mutex.clone();
    ///
    /// thread::spawn(move || {
    ///     *c_mutex.lock().unwrap() = 10;
    /// }).join().expect("thread::spawn failed");
    /// assert_eq!(*mutex.lock().unwrap(), 10);
    /// ```
B
Brian Anderson 已提交
227
    #[stable(feature = "rust1", since = "1.0.0")]
228
    pub fn lock(&self) -> LockResult<MutexGuard<T>> {
229
        unsafe {
A
Alex Crichton 已提交
230 231
            self.inner.lock();
            MutexGuard::new(self)
232
        }
A
Alex Crichton 已提交
233 234 235 236
    }

    /// Attempts to acquire this lock.
    ///
G
Guillaume Gomez 已提交
237
    /// If the lock could not be acquired at this time, then [`Err`] is returned.
A
Alex Crichton 已提交
238 239 240 241 242
    /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
    /// guard is dropped.
    ///
    /// This function does not block.
    ///
243
    /// # Errors
A
Alex Crichton 已提交
244 245
    ///
    /// If another user of this mutex panicked while holding the mutex, then
246
    /// this call will return failure if the mutex would otherwise be
A
Alex Crichton 已提交
247
    /// acquired.
248
    ///
G
Guillaume Gomez 已提交
249 250
    /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
    ///
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    /// # Examples
    ///
    /// ```
    /// use std::sync::{Arc, Mutex};
    /// use std::thread;
    ///
    /// let mutex = Arc::new(Mutex::new(0));
    /// let c_mutex = mutex.clone();
    ///
    /// thread::spawn(move || {
    ///     let mut lock = c_mutex.try_lock();
    ///     if let Ok(ref mut mutex) = lock {
    ///         **mutex = 10;
    ///     } else {
    ///         println!("try_lock failed");
    ///     }
    /// }).join().expect("thread::spawn failed");
    /// assert_eq!(*mutex.lock().unwrap(), 10);
    /// ```
B
Brian Anderson 已提交
270
    #[stable(feature = "rust1", since = "1.0.0")]
271
    pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
272
        unsafe {
A
Alex Crichton 已提交
273 274
            if self.inner.try_lock() {
                Ok(MutexGuard::new(self)?)
275 276 277
            } else {
                Err(TryLockError::WouldBlock)
            }
A
Alex Crichton 已提交
278
        }
279
    }
280

G
Guillaume Gomez 已提交
281
    /// Determines whether the mutex is poisoned.
282
    ///
G
Guillaume Gomez 已提交
283
    /// If another thread is active, the mutex can still become poisoned at any
284
    /// time. You should not trust a `false` value for program correctness
285
    /// without additional synchronization.
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::{Arc, Mutex};
    /// use std::thread;
    ///
    /// let mutex = Arc::new(Mutex::new(0));
    /// let c_mutex = mutex.clone();
    ///
    /// let _ = thread::spawn(move || {
    ///     let _lock = c_mutex.lock().unwrap();
    ///     panic!(); // the mutex gets poisoned
    /// }).join();
    /// assert_eq!(mutex.is_poisoned(), true);
    /// ```
302
    #[inline]
303
    #[stable(feature = "sync_poison", since = "1.2.0")]
304
    pub fn is_poisoned(&self) -> bool {
A
Alex Crichton 已提交
305
        self.poison.get()
306
    }
307 308 309

    /// Consumes this mutex, returning the underlying data.
    ///
310
    /// # Errors
311 312 313
    ///
    /// If another user of this mutex panicked while holding the mutex, then
    /// this call will return an error instead.
314 315 316 317 318 319 320 321 322
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Mutex;
    ///
    /// let mutex = Mutex::new(0);
    /// assert_eq!(mutex.into_inner().unwrap(), 0);
    /// ```
323
    #[stable(feature = "mutex_into_inner", since = "1.6.0")]
324 325
    pub fn into_inner(self) -> LockResult<T> where T: Sized {
        // We know statically that there are no outstanding references to
G
Guillaume Gomez 已提交
326
        // `self` so there's no need to lock the inner mutex.
327 328 329 330 331
        //
        // To get the inner value, we'd like to call `data.into_inner()`,
        // but because `Mutex` impl-s `Drop`, we can't move out of it, so
        // we'll have to destructure it manually instead.
        unsafe {
A
Alex Crichton 已提交
332 333 334 335
            // Like `let Mutex { inner, poison, data } = self`.
            let (inner, poison, data) = {
                let Mutex { ref inner, ref poison, ref data } = self;
                (ptr::read(inner), ptr::read(poison), ptr::read(data))
336 337
            };
            mem::forget(self);
A
Alex Crichton 已提交
338 339
            inner.destroy();  // Keep in sync with the `Drop` impl.
            drop(inner);
340

A
Alex Crichton 已提交
341
            poison::map_result(poison.borrow(), |_| data.into_inner())
342 343 344 345 346 347 348 349
        }
    }

    /// Returns a mutable reference to the underlying data.
    ///
    /// Since this call borrows the `Mutex` mutably, no actual locking needs to
    /// take place---the mutable borrow statically guarantees no locks exist.
    ///
350
    /// # Errors
351 352 353
    ///
    /// If another user of this mutex panicked while holding the mutex, then
    /// this call will return an error instead.
354 355 356 357 358 359 360 361 362 363
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Mutex;
    ///
    /// let mut mutex = Mutex::new(0);
    /// *mutex.get_mut().unwrap() = 10;
    /// assert_eq!(*mutex.lock().unwrap(), 10);
    /// ```
364
    #[stable(feature = "mutex_get_mut", since = "1.6.0")]
365 366
    pub fn get_mut(&mut self) -> LockResult<&mut T> {
        // We know statically that there are no other references to `self`, so
G
Guillaume Gomez 已提交
367
        // there's no need to lock the inner mutex.
368
        let data = unsafe { &mut *self.data.get() };
A
Alex Crichton 已提交
369
        poison::map_result(self.poison.borrow(), |_| data )
370
    }
A
Alex Crichton 已提交
371
}
372

B
Brian Anderson 已提交
373
#[stable(feature = "rust1", since = "1.0.0")]
374
unsafe impl<#[may_dangle] T: ?Sized> Drop for Mutex<T> {
A
Alex Crichton 已提交
375 376 377 378
    fn drop(&mut self) {
        // This is actually safe b/c we know that there is no further usage of
        // this mutex (it's up to the user to arrange for a mutex to get
        // dropped, that's not our job)
379 380
        //
        // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`.
A
Alex Crichton 已提交
381
        unsafe { self.inner.destroy() }
A
Alex Crichton 已提交
382 383 384
    }
}

385
#[stable(feature = "mutex_from", since = "1.24.0")]
E
Eduardo Pinho 已提交
386 387 388 389 390 391 392 393 394 395
impl<T> From<T> for Mutex<T> {
    /// Creates a new mutex in an unlocked state ready for use.
    /// This is equivalent to [`Mutex::new`].
    ///
    /// [`Mutex::new`]: #method.new
    fn from(t: T) -> Self {
        Mutex::new(t)
    }
}

396
#[stable(feature = "mutex_default", since = "1.10.0")]
397
impl<T: ?Sized + Default> Default for Mutex<T> {
398
    /// Creates a `Mutex<T>`, with the `Default` value for T.
399 400 401 402 403
    fn default() -> Mutex<T> {
        Mutex::new(Default::default())
    }
}

404
#[stable(feature = "rust1", since = "1.0.0")]
405
impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
406 407
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.try_lock() {
408
            Ok(guard) => f.debug_struct("Mutex").field("data", &&*guard).finish(),
409
            Err(TryLockError::Poisoned(err)) => {
410
                f.debug_struct("Mutex").field("data", &&**err.get_ref()).finish()
411
            },
412 413 414 415 416 417 418 419
            Err(TryLockError::WouldBlock) => {
                struct LockedPlaceholder;
                impl fmt::Debug for LockedPlaceholder {
                    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("<locked>") }
                }

                f.debug_struct("Mutex").field("data", &LockedPlaceholder).finish()
            }
420 421 422 423
        }
    }
}

424
impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
A
Alex Crichton 已提交
425
    unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
426 427 428 429 430 431 432
        poison::map_result(lock.poison.borrow(), |guard| {
            MutexGuard {
                __lock: lock,
                __poison: guard,
            }
        })
    }
A
Alex Crichton 已提交
433
}
434

B
Brian Anderson 已提交
435
#[stable(feature = "rust1", since = "1.0.0")]
436
impl<'mutex, T: ?Sized> Deref for MutexGuard<'mutex, T> {
437 438
    type Target = T;

A
Alex Crichton 已提交
439 440 441
    fn deref(&self) -> &T {
        unsafe { &*self.__lock.data.get() }
    }
A
Alex Crichton 已提交
442
}
443

B
Brian Anderson 已提交
444
#[stable(feature = "rust1", since = "1.0.0")]
445
impl<'mutex, T: ?Sized> DerefMut for MutexGuard<'mutex, T> {
A
Alex Crichton 已提交
446 447 448
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.__lock.data.get() }
    }
A
Alex Crichton 已提交
449 450
}

B
Brian Anderson 已提交
451
#[stable(feature = "rust1", since = "1.0.0")]
452
impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> {
453
    #[inline]
454 455 456
    fn drop(&mut self) {
        unsafe {
            self.__lock.poison.done(&self.__poison);
A
Alex Crichton 已提交
457
            self.__lock.inner.unlock();
458 459 460 461
        }
    }
}

462
#[stable(feature = "std_debug", since = "1.16.0")]
463 464 465 466 467 468 469 470
impl<'a, T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("MutexGuard")
            .field("lock", &self.__lock)
            .finish()
    }
}

471
#[stable(feature = "std_guard_impls", since = "1.20.0")]
472 473 474 475 476 477
impl<'a, T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        (**self).fmt(f)
    }
}

478
pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
A
Alex Crichton 已提交
479
    &guard.__lock.inner
480 481
}

482
pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
483
    &guard.__lock.poison
484 485
}

486
#[cfg(all(test, not(target_os = "emscripten")))]
487
mod tests {
488
    use sync::mpsc::channel;
A
Alex Crichton 已提交
489
    use sync::{Arc, Mutex, Condvar};
490
    use sync::atomic::{AtomicUsize, Ordering};
A
Aaron Turon 已提交
491
    use thread;
492

493
    struct Packet<T>(Arc<(Mutex<T>, Condvar)>);
494

495 496 497
    #[derive(Eq, PartialEq, Debug)]
    struct NonCopy(i32);

498 499
    #[test]
    fn smoke() {
A
Alex Crichton 已提交
500
        let m = Mutex::new(());
501 502
        drop(m.lock().unwrap());
        drop(m.lock().unwrap());
503 504 505 506
    }

    #[test]
    fn lots_and_lots() {
507 508
        const J: u32 = 1000;
        const K: u32 = 3;
509

A
Alex Crichton 已提交
510 511 512
        let m = Arc::new(Mutex::new(0));

        fn inc(m: &Mutex<u32>) {
513
            for _ in 0..J {
A
Alex Crichton 已提交
514
                *m.lock().unwrap() += 1;
515 516 517
            }
        }

518
        let (tx, rx) = channel();
519
        for _ in 0..K {
520
            let tx2 = tx.clone();
A
Alex Crichton 已提交
521 522
            let m2 = m.clone();
            thread::spawn(move|| { inc(&m2); tx2.send(()).unwrap(); });
523
            let tx2 = tx.clone();
A
Alex Crichton 已提交
524 525
            let m2 = m.clone();
            thread::spawn(move|| { inc(&m2); tx2.send(()).unwrap(); });
526 527
        }

528
        drop(tx);
529
        for _ in 0..2 * K {
530
            rx.recv().unwrap();
531
        }
A
Alex Crichton 已提交
532
        assert_eq!(*m.lock().unwrap(), J * K * 2);
533 534 535
    }

    #[test]
A
Alex Crichton 已提交
536 537
    fn try_lock() {
        let m = Mutex::new(());
538
        *m.try_lock().unwrap() = ();
539
    }
A
Alex Crichton 已提交
540

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    #[test]
    fn test_into_inner() {
        let m = Mutex::new(NonCopy(10));
        assert_eq!(m.into_inner().unwrap(), NonCopy(10));
    }

    #[test]
    fn test_into_inner_drop() {
        struct Foo(Arc<AtomicUsize>);
        impl Drop for Foo {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }
        let num_drops = Arc::new(AtomicUsize::new(0));
        let m = Mutex::new(Foo(num_drops.clone()));
        assert_eq!(num_drops.load(Ordering::SeqCst), 0);
        {
            let _inner = m.into_inner().unwrap();
            assert_eq!(num_drops.load(Ordering::SeqCst), 0);
        }
        assert_eq!(num_drops.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_into_inner_poison() {
        let m = Arc::new(Mutex::new(NonCopy(10)));
        let m2 = m.clone();
        let _ = thread::spawn(move || {
            let _lock = m2.lock().unwrap();
            panic!("test panic in inner thread to poison mutex");
        }).join();

        assert!(m.is_poisoned());
        match Arc::try_unwrap(m).unwrap().into_inner() {
            Err(e) => assert_eq!(e.into_inner(), NonCopy(10)),
            Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {:?}", x),
        }
    }

    #[test]
    fn test_get_mut() {
        let mut m = Mutex::new(NonCopy(10));
        *m.get_mut().unwrap() = NonCopy(20);
        assert_eq!(m.into_inner().unwrap(), NonCopy(20));
    }

    #[test]
    fn test_get_mut_poison() {
        let m = Arc::new(Mutex::new(NonCopy(10)));
        let m2 = m.clone();
        let _ = thread::spawn(move || {
            let _lock = m2.lock().unwrap();
            panic!("test panic in inner thread to poison mutex");
        }).join();

        assert!(m.is_poisoned());
        match Arc::try_unwrap(m).unwrap().get_mut() {
            Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)),
            Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {:?}", x),
        }
    }

A
Alex Crichton 已提交
604 605
    #[test]
    fn test_mutex_arc_condvar() {
606 607
        let packet = Packet(Arc::new((Mutex::new(false), Condvar::new())));
        let packet2 = Packet(packet.0.clone());
A
Alex Crichton 已提交
608
        let (tx, rx) = channel();
A
Aaron Turon 已提交
609
        let _t = thread::spawn(move|| {
A
Alex Crichton 已提交
610
            // wait until parent gets in
611
            rx.recv().unwrap();
612
            let &(ref lock, ref cvar) = &*packet2.0;
613
            let mut lock = lock.lock().unwrap();
A
Alex Crichton 已提交
614 615 616 617
            *lock = true;
            cvar.notify_one();
        });

618
        let &(ref lock, ref cvar) = &*packet.0;
619
        let mut lock = lock.lock().unwrap();
620
        tx.send(()).unwrap();
A
Alex Crichton 已提交
621 622
        assert!(!*lock);
        while !*lock {
623
            lock = cvar.wait(lock).unwrap();
A
Alex Crichton 已提交
624 625 626 627 628
        }
    }

    #[test]
    fn test_arc_condvar_poison() {
T
Tobias Bucher 已提交
629
        let packet = Packet(Arc::new((Mutex::new(1), Condvar::new())));
630
        let packet2 = Packet(packet.0.clone());
A
Alex Crichton 已提交
631 632
        let (tx, rx) = channel();

A
Aaron Turon 已提交
633
        let _t = thread::spawn(move || -> () {
634
            rx.recv().unwrap();
635
            let &(ref lock, ref cvar) = &*packet2.0;
636
            let _g = lock.lock().unwrap();
A
Alex Crichton 已提交
637 638 639 640 641
            cvar.notify_one();
            // Parent should fail when it wakes up.
            panic!();
        });

642
        let &(ref lock, ref cvar) = &*packet.0;
643
        let mut lock = lock.lock().unwrap();
644
        tx.send(()).unwrap();
A
Alex Crichton 已提交
645
        while *lock == 1 {
646 647 648 649 650 651 652
            match cvar.wait(lock) {
                Ok(l) => {
                    lock = l;
                    assert_eq!(*lock, 1);
                }
                Err(..) => break,
            }
A
Alex Crichton 已提交
653 654 655 656 657
        }
    }

    #[test]
    fn test_mutex_arc_poison() {
T
Tobias Bucher 已提交
658
        let arc = Arc::new(Mutex::new(1));
659
        assert!(!arc.is_poisoned());
A
Alex Crichton 已提交
660
        let arc2 = arc.clone();
A
Aaron Turon 已提交
661
        let _ = thread::spawn(move|| {
662
            let lock = arc2.lock().unwrap();
A
Alex Crichton 已提交
663
            assert_eq!(*lock, 2);
A
Aaron Turon 已提交
664
        }).join();
665
        assert!(arc.lock().is_err());
666
        assert!(arc.is_poisoned());
A
Alex Crichton 已提交
667 668 669 670 671 672
    }

    #[test]
    fn test_mutex_arc_nested() {
        // Tests nested mutexes and access
        // to underlying data.
T
Tobias Bucher 已提交
673
        let arc = Arc::new(Mutex::new(1));
A
Alex Crichton 已提交
674 675
        let arc2 = Arc::new(Mutex::new(arc));
        let (tx, rx) = channel();
A
Aaron Turon 已提交
676
        let _t = thread::spawn(move|| {
677
            let lock = arc2.lock().unwrap();
678
            let lock2 = lock.lock().unwrap();
A
Alex Crichton 已提交
679
            assert_eq!(*lock2, 1);
680
            tx.send(()).unwrap();
A
Alex Crichton 已提交
681
        });
682
        rx.recv().unwrap();
A
Alex Crichton 已提交
683 684 685 686
    }

    #[test]
    fn test_mutex_arc_access_in_unwind() {
T
Tobias Bucher 已提交
687
        let arc = Arc::new(Mutex::new(1));
A
Alex Crichton 已提交
688
        let arc2 = arc.clone();
A
Aaron Turon 已提交
689
        let _ = thread::spawn(move|| -> () {
A
Alex Crichton 已提交
690
            struct Unwinder {
N
Nick Cameron 已提交
691
                i: Arc<Mutex<i32>>,
A
Alex Crichton 已提交
692 693 694
            }
            impl Drop for Unwinder {
                fn drop(&mut self) {
695
                    *self.i.lock().unwrap() += 1;
A
Alex Crichton 已提交
696 697 698 699
                }
            }
            let _u = Unwinder { i: arc2 };
            panic!();
A
Aaron Turon 已提交
700
        }).join();
701
        let lock = arc.lock().unwrap();
A
Alex Crichton 已提交
702 703
        assert_eq!(*lock, 2);
    }
704

705 706 707 708 709 710 711 712 713 714 715
    #[test]
    fn test_mutex_unsized() {
        let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]);
        {
            let b = &mut *mutex.lock().unwrap();
            b[0] = 4;
            b[2] = 5;
        }
        let comp: &[i32] = &[4, 2, 5];
        assert_eq!(&*mutex.lock().unwrap(), comp);
    }
716
}