mutex.rs 16.9 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.

11
use prelude::v1::*;
12

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

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

125 126
// these are the only places where `T: Send` matters; all other
// functionality works fine on a single thread.
127
unsafe impl<T: Send> Send for Mutex<T> { }
F
Flavio Percoco 已提交
128

129
unsafe impl<T: Send> Sync for Mutex<T> { }
F
Flavio Percoco 已提交
130

131 132 133 134 135 136 137 138
/// The static mutex type is provided to allow for static allocation of mutexes.
///
/// Note that this is a separate type because using a Mutex correctly means that
/// it needs to have a destructor run. In Rust, statics are not allowed to have
/// destructors. As a result, a `StaticMutex` has one extra method when compared
/// to a `Mutex`, a `destroy` method. This method is unsafe to call, and
/// documentation can be found directly on the method.
///
S
Steve Klabnik 已提交
139
/// # Examples
140
///
141
/// ```
142
/// # #![feature(std_misc)]
A
Alex Crichton 已提交
143
/// use std::sync::{StaticMutex, MUTEX_INIT};
144
///
A
Alex Crichton 已提交
145
/// static LOCK: StaticMutex = MUTEX_INIT;
146
///
A
Alex Crichton 已提交
147
/// {
148
///     let _g = LOCK.lock().unwrap();
149 150 151 152
///     // do some productive work
/// }
/// // lock is unlocked here.
/// ```
153
#[unstable(feature = "std_misc",
154
           reason = "may be merged with Mutex in the future")]
155
pub struct StaticMutex {
A
Alex Crichton 已提交
156
    lock: sys::Mutex,
157
    poison: poison::Flag,
158 159 160 161
}

/// 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 已提交
162 163
///
/// The data protected by the mutex can be access through this guard via its
164
/// `Deref` and `DerefMut` implementations
165
#[must_use]
B
Brian Anderson 已提交
166
#[stable(feature = "rust1", since = "1.0.0")]
A
Alex Crichton 已提交
167 168 169
pub struct MutexGuard<'a, T: 'a> {
    // funny underscores due to how Deref/DerefMut currently work (they
    // disregard field privacy).
170 171 172
    __lock: &'a StaticMutex,
    __data: &'a UnsafeCell<T>,
    __poison: poison::Guard,
173 174
}

175 176
impl<'a, T> !marker::Send for MutexGuard<'a, T> {}

177 178
/// Static initialization of a mutex. This constant can be used to initialize
/// other mutex constants.
179
#[unstable(feature = "std_misc",
180
           reason = "may be merged with Mutex in the future")]
A
Alex Crichton 已提交
181
pub const MUTEX_INIT: StaticMutex = StaticMutex {
A
Alex Crichton 已提交
182
    lock: sys::MUTEX_INIT,
183
    poison: poison::FLAG_INIT,
184 185
};

186
impl<T> Mutex<T> {
A
Alex Crichton 已提交
187
    /// Creates a new mutex in an unlocked state ready for use.
B
Brian Anderson 已提交
188
    #[stable(feature = "rust1", since = "1.0.0")]
A
Alex Crichton 已提交
189 190 191
    pub fn new(t: T) -> Mutex<T> {
        Mutex {
            inner: box MUTEX_INIT,
192
            data: UnsafeCell::new(t),
A
Alex Crichton 已提交
193 194 195 196 197 198 199 200 201 202
        }
    }

    /// Acquires a mutex, blocking the current task until it is able to do so.
    ///
    /// This function will block the local task until it is available to acquire
    /// the mutex. Upon returning, the task is the only task with the mutex
    /// 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.
    ///
203
    /// # Failure
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.
B
Brian Anderson 已提交
207
    #[stable(feature = "rust1", since = "1.0.0")]
208 209
    pub fn lock(&self) -> LockResult<MutexGuard<T>> {
        unsafe { self.inner.lock.lock() }
210
        MutexGuard::new(&*self.inner, &self.data)
A
Alex Crichton 已提交
211 212 213 214
    }

    /// Attempts to acquire this lock.
    ///
215
    /// If the lock could not be acquired at this time, then `Err` is returned.
A
Alex Crichton 已提交
216 217 218 219 220
    /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
    /// guard is dropped.
    ///
    /// This function does not block.
    ///
221
    /// # Failure
A
Alex Crichton 已提交
222 223
    ///
    /// If another user of this mutex panicked while holding the mutex, then
224
    /// this call will return failure if the mutex would otherwise be
A
Alex Crichton 已提交
225
    /// acquired.
B
Brian Anderson 已提交
226
    #[stable(feature = "rust1", since = "1.0.0")]
227 228
    pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
        if unsafe { self.inner.lock.try_lock() } {
229
            Ok(try!(MutexGuard::new(&*self.inner, &self.data)))
230 231
        } else {
            Err(TryLockError::WouldBlock)
A
Alex Crichton 已提交
232
        }
233
    }
234

235
    /// Determines whether the lock is poisoned.
236 237 238 239 240 241 242 243 244
    ///
    /// If another thread is active, the lock can still become poisoned at any
    /// time.  You should not trust a `false` value for program correctness
    /// without additional synchronization.
    #[inline]
    #[unstable(feature = "std_misc")]
    pub fn is_poisoned(&self) -> bool {
        self.inner.poison.get()
    }
A
Alex Crichton 已提交
245
}
246

B
Brian Anderson 已提交
247
#[stable(feature = "rust1", since = "1.0.0")]
248
impl<T> Drop for Mutex<T> {
A
Alex Crichton 已提交
249 250 251 252 253 254 255 256
    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)
        unsafe { self.inner.lock.destroy() }
    }
}

257
#[stable(feature = "rust1", since = "1.0.0")]
258
impl<T: fmt::Debug + 'static> fmt::Debug for Mutex<T> {
259 260 261 262 263 264 265 266 267 268 269
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.try_lock() {
            Ok(guard) => write!(f, "Mutex {{ data: {:?} }}", *guard),
            Err(TryLockError::Poisoned(err)) => {
                write!(f, "Mutex {{ data: Poisoned({:?}) }}", **err.get_ref())
            },
            Err(TryLockError::WouldBlock) => write!(f, "Mutex {{ <locked> }}")
        }
    }
}

A
Alex Crichton 已提交
270 271 272
struct Dummy(UnsafeCell<()>);
unsafe impl Sync for Dummy {}
static DUMMY: Dummy = Dummy(UnsafeCell { value: () });
273

A
Alex Crichton 已提交
274
impl StaticMutex {
275
    /// Acquires this lock, see `Mutex::lock`
276
    #[inline]
277
    #[unstable(feature = "std_misc",
278
               reason = "may be merged with Mutex in the future")]
279
    pub fn lock(&'static self) -> LockResult<MutexGuard<()>> {
A
Alex Crichton 已提交
280
        unsafe { self.lock.lock() }
A
Alex Crichton 已提交
281
        MutexGuard::new(self, &DUMMY.0)
A
Alex Crichton 已提交
282 283 284
    }

    /// Attempts to grab this lock, see `Mutex::try_lock`
285
    #[inline]
286
    #[unstable(feature = "std_misc",
287
               reason = "may be merged with Mutex in the future")]
288
    pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> {
A
Alex Crichton 已提交
289
        if unsafe { self.lock.try_lock() } {
A
Alex Crichton 已提交
290
            Ok(try!(MutexGuard::new(self, &DUMMY.0)))
A
Alex Crichton 已提交
291
        } else {
292
            Err(TryLockError::WouldBlock)
A
Alex Crichton 已提交
293
        }
294 295 296 297 298 299 300 301 302 303 304 305
    }

    /// Deallocates resources associated with this static mutex.
    ///
    /// This method is unsafe because it provides no guarantees that there are
    /// no active users of this mutex, and safety is not guaranteed if there are
    /// active users of this mutex.
    ///
    /// This method is required to ensure that there are no memory leaks on
    /// *all* platforms. It may be the case that some platforms do not leak
    /// memory if this method is not called, but this is not guaranteed to be
    /// true on all platforms.
306
    #[unstable(feature = "std_misc",
307
               reason = "may be merged with Mutex in the future")]
A
Alex Crichton 已提交
308
    pub unsafe fn destroy(&'static self) {
309 310 311 312
        self.lock.destroy()
    }
}

A
Alex Crichton 已提交
313
impl<'mutex, T> MutexGuard<'mutex, T> {
314 315 316 317 318 319 320 321 322 323 324

    fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>)
           -> LockResult<MutexGuard<'mutex, T>> {
        poison::map_result(lock.poison.borrow(), |guard| {
            MutexGuard {
                __lock: lock,
                __data: data,
                __poison: guard,
            }
        })
    }
A
Alex Crichton 已提交
325
}
326

B
Brian Anderson 已提交
327
#[stable(feature = "rust1", since = "1.0.0")]
328 329 330
impl<'mutex, T> Deref for MutexGuard<'mutex, T> {
    type Target = T;

331
    fn deref<'a>(&'a self) -> &'a T {
332
        unsafe { &*self.__data.get() }
333
    }
A
Alex Crichton 已提交
334
}
B
Brian Anderson 已提交
335
#[stable(feature = "rust1", since = "1.0.0")]
336
impl<'mutex, T> DerefMut for MutexGuard<'mutex, T> {
A
Alex Crichton 已提交
337
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
338
        unsafe { &mut *self.__data.get() }
A
Alex Crichton 已提交
339 340 341
    }
}

B
Brian Anderson 已提交
342
#[stable(feature = "rust1", since = "1.0.0")]
343
impl<'a, T> Drop for MutexGuard<'a, T> {
344
    #[inline]
345 346 347 348
    fn drop(&mut self) {
        unsafe {
            self.__lock.poison.done(&self.__poison);
            self.__lock.lock.unlock();
349 350 351 352
        }
    }
}

353 354
pub fn guard_lock<'a, T>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
    &guard.__lock.lock
355 356
}

357 358
pub fn guard_poison<'a, T>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
    &guard.__lock.poison
359 360 361
}

#[cfg(test)]
362
mod tests {
363
    use prelude::v1::*;
A
Alex Crichton 已提交
364

365
    use sync::mpsc::channel;
A
Alex Crichton 已提交
366
    use sync::{Arc, Mutex, StaticMutex, MUTEX_INIT, Condvar};
A
Aaron Turon 已提交
367
    use thread;
368

369
    struct Packet<T: Send>(Arc<(Mutex<T>, Condvar)>);
370

371
    unsafe impl<T: Send> Send for Packet<T> {}
372 373
    unsafe impl<T> Sync for Packet<T> {}

374 375
    #[test]
    fn smoke() {
A
Alex Crichton 已提交
376
        let m = Mutex::new(());
377 378
        drop(m.lock().unwrap());
        drop(m.lock().unwrap());
379 380 381 382
    }

    #[test]
    fn smoke_static() {
N
NODA, Kai 已提交
383
        static M: StaticMutex = MUTEX_INIT;
384
        unsafe {
385 386
            drop(M.lock().unwrap());
            drop(M.lock().unwrap());
N
NODA, Kai 已提交
387
            M.destroy();
388 389 390 391 392
        }
    }

    #[test]
    fn lots_and_lots() {
N
NODA, Kai 已提交
393
        static M: StaticMutex = MUTEX_INIT;
N
Nick Cameron 已提交
394
        static mut CNT: u32 = 0;
395 396
        const J: u32 = 1000;
        const K: u32 = 3;
397 398

        fn inc() {
399
            for _ in 0..J {
400
                unsafe {
401
                    let _g = M.lock().unwrap();
402 403 404 405 406
                    CNT += 1;
                }
            }
        }

407
        let (tx, rx) = channel();
408
        for _ in 0..K {
409
            let tx2 = tx.clone();
A
Aaron Turon 已提交
410
            thread::spawn(move|| { inc(); tx2.send(()).unwrap(); });
411
            let tx2 = tx.clone();
A
Aaron Turon 已提交
412
            thread::spawn(move|| { inc(); tx2.send(()).unwrap(); });
413 414
        }

415
        drop(tx);
416
        for _ in 0..2 * K {
417
            rx.recv().unwrap();
418
        }
N
NODA, Kai 已提交
419
        assert_eq!(unsafe {CNT}, J * K * 2);
420
        unsafe {
N
NODA, Kai 已提交
421
            M.destroy();
422 423 424 425
        }
    }

    #[test]
A
Alex Crichton 已提交
426 427
    fn try_lock() {
        let m = Mutex::new(());
428
        *m.try_lock().unwrap() = ();
429
    }
A
Alex Crichton 已提交
430 431 432

    #[test]
    fn test_mutex_arc_condvar() {
433 434
        let packet = Packet(Arc::new((Mutex::new(false), Condvar::new())));
        let packet2 = Packet(packet.0.clone());
A
Alex Crichton 已提交
435
        let (tx, rx) = channel();
A
Aaron Turon 已提交
436
        let _t = thread::spawn(move|| {
A
Alex Crichton 已提交
437
            // wait until parent gets in
438
            rx.recv().unwrap();
439
            let &(ref lock, ref cvar) = &*packet2.0;
440
            let mut lock = lock.lock().unwrap();
A
Alex Crichton 已提交
441 442 443 444
            *lock = true;
            cvar.notify_one();
        });

445
        let &(ref lock, ref cvar) = &*packet.0;
446
        let mut lock = lock.lock().unwrap();
447
        tx.send(()).unwrap();
A
Alex Crichton 已提交
448 449
        assert!(!*lock);
        while !*lock {
450
            lock = cvar.wait(lock).unwrap();
A
Alex Crichton 已提交
451 452 453 454 455
        }
    }

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

A
Aaron Turon 已提交
460
        let _t = thread::spawn(move || -> () {
461
            rx.recv().unwrap();
462
            let &(ref lock, ref cvar) = &*packet2.0;
463
            let _g = lock.lock().unwrap();
A
Alex Crichton 已提交
464 465 466 467 468
            cvar.notify_one();
            // Parent should fail when it wakes up.
            panic!();
        });

469
        let &(ref lock, ref cvar) = &*packet.0;
470
        let mut lock = lock.lock().unwrap();
471
        tx.send(()).unwrap();
A
Alex Crichton 已提交
472
        while *lock == 1 {
473 474 475 476 477 478 479
            match cvar.wait(lock) {
                Ok(l) => {
                    lock = l;
                    assert_eq!(*lock, 1);
                }
                Err(..) => break,
            }
A
Alex Crichton 已提交
480 481 482 483 484
        }
    }

    #[test]
    fn test_mutex_arc_poison() {
T
Tobias Bucher 已提交
485
        let arc = Arc::new(Mutex::new(1));
486
        assert!(!arc.is_poisoned());
A
Alex Crichton 已提交
487
        let arc2 = arc.clone();
A
Aaron Turon 已提交
488
        let _ = thread::spawn(move|| {
489
            let lock = arc2.lock().unwrap();
A
Alex Crichton 已提交
490
            assert_eq!(*lock, 2);
A
Aaron Turon 已提交
491
        }).join();
492
        assert!(arc.lock().is_err());
493
        assert!(arc.is_poisoned());
A
Alex Crichton 已提交
494 495 496 497 498 499
    }

    #[test]
    fn test_mutex_arc_nested() {
        // Tests nested mutexes and access
        // to underlying data.
T
Tobias Bucher 已提交
500
        let arc = Arc::new(Mutex::new(1));
A
Alex Crichton 已提交
501 502
        let arc2 = Arc::new(Mutex::new(arc));
        let (tx, rx) = channel();
A
Aaron Turon 已提交
503
        let _t = thread::spawn(move|| {
504
            let lock = arc2.lock().unwrap();
505
            let lock2 = lock.lock().unwrap();
A
Alex Crichton 已提交
506
            assert_eq!(*lock2, 1);
507
            tx.send(()).unwrap();
A
Alex Crichton 已提交
508
        });
509
        rx.recv().unwrap();
A
Alex Crichton 已提交
510 511 512 513
    }

    #[test]
    fn test_mutex_arc_access_in_unwind() {
T
Tobias Bucher 已提交
514
        let arc = Arc::new(Mutex::new(1));
A
Alex Crichton 已提交
515
        let arc2 = arc.clone();
A
Aaron Turon 已提交
516
        let _ = thread::spawn(move|| -> () {
A
Alex Crichton 已提交
517
            struct Unwinder {
N
Nick Cameron 已提交
518
                i: Arc<Mutex<i32>>,
A
Alex Crichton 已提交
519 520 521
            }
            impl Drop for Unwinder {
                fn drop(&mut self) {
522
                    *self.i.lock().unwrap() += 1;
A
Alex Crichton 已提交
523 524 525 526
                }
            }
            let _u = Unwinder { i: arc2 };
            panic!();
A
Aaron Turon 已提交
527
        }).join();
528
        let lock = arc.lock().unwrap();
A
Alex Crichton 已提交
529 530
        assert_eq!(*lock, 2);
    }
531
}