1// Copyright 2016 Amanieu d'Antras
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
78use crate::raw_mutex::RawMutex;
9use core::num::NonZeroUsize;
10use lock_api::{self, GetThreadId};
1112/// Implementation of the `GetThreadId` trait for `lock_api::ReentrantMutex`.
13pub struct RawThreadId;
1415unsafe impl GetThreadId for RawThreadId {
16const INIT: RawThreadId = RawThreadId;
1718fn nonzero_thread_id(&self) -> NonZeroUsize {
19// The address of a thread-local variable is guaranteed to be unique to the
20 // current thread, and is also guaranteed to be non-zero. The variable has to have a
21 // non-zero size to guarantee it has a unique address for each thread.
22thread_local!(static KEY: u8 = 0);
23 KEY.with(|x| {
24 NonZeroUsize::new(x as *const _ as usize)
25 .expect("thread-local variable address is null")
26 })
27 }
28}
2930/// A mutex which can be recursively locked by a single thread.
31///
32/// This type is identical to `Mutex` except for the following points:
33///
34/// - Locking multiple times from the same thread will work correctly instead of
35/// deadlocking.
36/// - `ReentrantMutexGuard` does not give mutable references to the locked data.
37/// Use a `RefCell` if you need this.
38///
39/// See [`Mutex`](type.Mutex.html) for more details about the underlying mutex
40/// primitive.
41pub type ReentrantMutex<T> = lock_api::ReentrantMutex<RawMutex, RawThreadId, T>;
4243/// Creates a new reentrant mutex in an unlocked state ready for use.
44///
45/// This allows creating a reentrant mutex in a constant context on stable Rust.
46pub const fn const_reentrant_mutex<T>(val: T) -> ReentrantMutex<T> {
47 ReentrantMutex::const_new(
48 <RawMutex as lock_api::RawMutex>::INIT,
49 <RawThreadId as lock_api::GetThreadId>::INIT,
50 val,
51 )
52}
5354/// An RAII implementation of a "scoped lock" of a reentrant mutex. When this structure
55/// is dropped (falls out of scope), the lock will be unlocked.
56///
57/// The data protected by the mutex can be accessed through this guard via its
58/// `Deref` implementation.
59pub type ReentrantMutexGuard<'a, T> = lock_api::ReentrantMutexGuard<'a, RawMutex, RawThreadId, T>;
6061/// An RAII mutex guard returned by `ReentrantMutexGuard::map`, which can point to a
62/// subfield of the protected data.
63///
64/// The main difference between `MappedReentrantMutexGuard` and `ReentrantMutexGuard` is that the
65/// former doesn't support temporarily unlocking and re-locking, since that
66/// could introduce soundness issues if the locked object is modified by another
67/// thread.
68pub type MappedReentrantMutexGuard<'a, T> =
69 lock_api::MappedReentrantMutexGuard<'a, RawMutex, RawThreadId, T>;
7071#[cfg(test)]
72mod tests {
73use crate::ReentrantMutex;
74use std::cell::RefCell;
75use std::sync::Arc;
76use std::thread;
7778#[cfg(feature = "serde")]
79use bincode::{deserialize, serialize};
8081#[test]
82fn smoke() {
83let m = ReentrantMutex::new(2);
84 {
85let a = m.lock();
86 {
87let b = m.lock();
88 {
89let c = m.lock();
90assert_eq!(*c, 2);
91 }
92assert_eq!(*b, 2);
93 }
94assert_eq!(*a, 2);
95 }
96 }
9798#[test]
99fn is_mutex() {
100let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
101let m2 = m.clone();
102let lock = m.lock();
103let child = thread::spawn(move || {
104let lock = m2.lock();
105assert_eq!(*lock.borrow(), 4950);
106 });
107for i in 0..100 {
108let lock = m.lock();
109*lock.borrow_mut() += i;
110 }
111 drop(lock);
112 child.join().unwrap();
113 }
114115#[test]
116fn trylock_works() {
117let m = Arc::new(ReentrantMutex::new(()));
118let m2 = m.clone();
119let _lock = m.try_lock();
120let _lock2 = m.try_lock();
121 thread::spawn(move || {
122let lock = m2.try_lock();
123assert!(lock.is_none());
124 })
125 .join()
126 .unwrap();
127let _lock3 = m.try_lock();
128 }
129130#[test]
131fn test_reentrant_mutex_debug() {
132let mutex = ReentrantMutex::new(vec![0u8, 10]);
133134assert_eq!(format!("{:?}", mutex), "ReentrantMutex { data: [0, 10] }");
135 }
136137#[cfg(feature = "serde")]
138 #[test]
139fn test_serde() {
140let contents: Vec<u8> = vec![0, 1, 2];
141let mutex = ReentrantMutex::new(contents.clone());
142143let serialized = serialize(&mutex).unwrap();
144let deserialized: ReentrantMutex<Vec<u8>> = deserialize(&serialized).unwrap();
145146assert_eq!(*(mutex.lock()), *(deserialized.lock()));
147assert_eq!(contents, *(deserialized.lock()));
148 }
149}