Skip to main content

std/sync/
reentrant_lock.rs

1use crate::cell::UnsafeCell;
2use crate::fmt;
3use crate::ops::Deref;
4use crate::panic::{RefUnwindSafe, UnwindSafe};
5use crate::sys::sync as sys;
6use crate::thread::{ThreadId, current_id};
7
8/// A re-entrant mutual exclusion lock
9///
10/// This lock will block *other* threads waiting for the lock to become
11/// available. The thread which has already locked the mutex can lock it
12/// multiple times without blocking, preventing a common source of deadlocks.
13///
14/// # Examples
15///
16/// Allow recursively calling a function needing synchronization from within
17/// a callback (this is how [`StdoutLock`](crate::io::StdoutLock) is currently
18/// implemented):
19///
20/// ```
21/// #![feature(reentrant_lock)]
22///
23/// use std::cell::RefCell;
24/// use std::sync::ReentrantLock;
25///
26/// pub struct Log {
27///     data: RefCell<String>,
28/// }
29///
30/// impl Log {
31///     pub fn append(&self, msg: &str) {
32///         self.data.borrow_mut().push_str(msg);
33///     }
34/// }
35///
36/// static LOG: ReentrantLock<Log> = ReentrantLock::new(Log { data: RefCell::new(String::new()) });
37///
38/// pub fn with_log<R>(f: impl FnOnce(&Log) -> R) -> R {
39///     let log = LOG.lock();
40///     f(&*log)
41/// }
42///
43/// with_log(|log| {
44///     log.append("Hello");
45///     with_log(|log| log.append(" there!"));
46/// });
47/// ```
48///
49// # Implementation details
50//
51// The 'owner' field tracks which thread has locked the mutex.
52//
53// We use thread::current_id() as the thread identifier, which is just the
54// current thread's ThreadId, so it's unique across the process lifetime.
55//
56// If `owner` is set to the identifier of the current thread,
57// we assume the mutex is already locked and instead of locking it again,
58// we increment `lock_count`.
59//
60// When unlocking, we decrement `lock_count`, and only unlock the mutex when
61// it reaches zero.
62//
63// `lock_count` is protected by the mutex and only accessed by the thread that has
64// locked the mutex, so needs no synchronization.
65//
66// `owner` can be checked by other threads that want to see if they already
67// hold the lock, so needs to be atomic. If it compares equal, we're on the
68// same thread that holds the mutex and memory access can use relaxed ordering
69// since we're not dealing with multiple threads. If it's not equal,
70// synchronization is left to the mutex, making relaxed memory ordering for
71// the `owner` field fine in all cases.
72//
73// On systems without 64 bit atomics we also store the address of a TLS variable
74// along the 64-bit TID. We then first check that address against the address
75// of that variable on the current thread, and only if they compare equal do we
76// compare the actual TIDs. Because we only ever read the TID on the same thread
77// that it was written on (or a thread sharing the TLS block with that writer thread),
78// we don't need to further synchronize the TID accesses, so they can be regular 64-bit
79// non-atomic accesses.
80#[unstable(feature = "reentrant_lock", issue = "121440")]
81pub struct ReentrantLock<T: ?Sized> {
82    mutex: sys::Mutex,
83    owner: Tid,
84    lock_count: UnsafeCell<u32>,
85    data: T,
86}
87
88cfg_select!(
89    target_has_atomic = "64" => {
90        use crate::sync::atomic::Ordering::Relaxed;
91        use crate::sync::atomic::{Atomic, AtomicU64};
92
93        struct Tid(Atomic<u64>);
94
95        impl Tid {
96            const fn new() -> Self {
97                Self(AtomicU64::new(0))
98            }
99
100            #[inline]
101            fn contains(&self, owner: ThreadId) -> bool {
102                owner.as_u64().get() == self.0.load(Relaxed)
103            }
104
105            #[inline]
106            // This is just unsafe to match the API of the Tid type below.
107            unsafe fn set(&self, tid: Option<ThreadId>) {
108                let value = tid.map_or(0, |tid| tid.as_u64().get());
109                self.0.store(value, Relaxed);
110            }
111        }
112    }
113    _ => {
114        /// Returns the address of a TLS variable. This is guaranteed to
115        /// be unique across all currently alive threads.
116        fn tls_addr() -> usize {
117            thread_local! { static X: u8 = const { 0u8 } };
118
119            X.with(|p| <*const u8>::addr(p))
120        }
121
122        use crate::sync::atomic::{Atomic, AtomicUsize, Ordering};
123
124        struct Tid {
125            // When a thread calls `set()`, this value gets updated to
126            // the address of a thread local on that thread. This is
127            // used as a first check in `contains()`; if the `tls_addr`
128            // doesn't match the TLS address of the current thread, then
129            // the ThreadId also can't match. Only if the TLS addresses do
130            // match do we read out the actual TID.
131            // Note also that we can use relaxed atomic operations here, because
132            // we only ever read from the tid if `tls_addr` matches the current
133            // TLS address. In that case, either the tid has been set by
134            // the current thread, or by a thread that has terminated before
135            // the current thread's `tls_addr` was allocated. In either case, no further
136            // synchronization is needed (as per <https://github.com/rust-lang/miri/issues/3450>)
137            tls_addr: Atomic<usize>,
138            tid: UnsafeCell<u64>,
139        }
140
141        unsafe impl Send for Tid {}
142        unsafe impl Sync for Tid {}
143
144        impl Tid {
145            const fn new() -> Self {
146                Self { tls_addr: AtomicUsize::new(0), tid: UnsafeCell::new(0) }
147            }
148
149            #[inline]
150            // NOTE: This assumes that `owner` is the ID of the current
151            // thread, and may spuriously return `false` if that's not the case.
152            fn contains(&self, owner: ThreadId) -> bool {
153                // We must call `tls_addr()` *before* doing the load to ensure that if we reuse an
154                // earlier thread's address, the `tls_addr.load()` below happens-after everything
155                // that thread did.
156                let tls_addr = tls_addr();
157                // SAFETY: See the comments in the struct definition.
158                self.tls_addr.load(Ordering::Relaxed) == tls_addr
159                    && unsafe { *self.tid.get() } == owner.as_u64().get()
160            }
161
162            #[inline]
163            // This may only be called by one thread at a time, and can lead to
164            // race conditions otherwise.
165            unsafe fn set(&self, tid: Option<ThreadId>) {
166                // It's important that we set `self.tls_addr` to 0 if the tid is
167                // cleared. Otherwise, there might be race conditions between
168                // `set()` and `get()`.
169                let tls_addr = if tid.is_some() { tls_addr() } else { 0 };
170                let value = tid.map_or(0, |tid| tid.as_u64().get());
171                self.tls_addr.store(tls_addr, Ordering::Relaxed);
172                unsafe { *self.tid.get() = value };
173            }
174        }
175    }
176);
177
178#[unstable(feature = "reentrant_lock", issue = "121440")]
179unsafe impl<T: Send + ?Sized> Send for ReentrantLock<T> {}
180#[unstable(feature = "reentrant_lock", issue = "121440")]
181unsafe impl<T: Send + ?Sized> Sync for ReentrantLock<T> {}
182
183// Because of the `UnsafeCell`, these traits are not implemented automatically
184#[unstable(feature = "reentrant_lock", issue = "121440")]
185impl<T: UnwindSafe + ?Sized> UnwindSafe for ReentrantLock<T> {}
186#[unstable(feature = "reentrant_lock", issue = "121440")]
187impl<T: RefUnwindSafe + ?Sized> RefUnwindSafe for ReentrantLock<T> {}
188
189/// An RAII implementation of a "scoped lock" of a re-entrant lock. When this
190/// structure is dropped (falls out of scope), the lock will be unlocked.
191///
192/// The data protected by the mutex can be accessed through this guard via its
193/// [`Deref`] implementation.
194///
195/// This structure is created by the [`lock`](ReentrantLock::lock) method on
196/// [`ReentrantLock`].
197///
198/// # Mutability
199///
200/// Unlike [`MutexGuard`](super::MutexGuard), `ReentrantLockGuard` does not
201/// implement [`DerefMut`](crate::ops::DerefMut), because implementation of
202/// the trait would violate Rust’s reference aliasing rules. Use interior
203/// mutability (usually [`RefCell`](crate::cell::RefCell)) in order to mutate
204/// the guarded data.
205#[must_use = "if unused the ReentrantLock will immediately unlock"]
206#[unstable(feature = "reentrant_lock", issue = "121440")]
207pub struct ReentrantLockGuard<'a, T: ?Sized + 'a> {
208    lock: &'a ReentrantLock<T>,
209}
210
211#[unstable(feature = "reentrant_lock", issue = "121440")]
212impl<T: ?Sized> !Send for ReentrantLockGuard<'_, T> {}
213
214#[unstable(feature = "reentrant_lock", issue = "121440")]
215unsafe impl<T: ?Sized + Sync> Sync for ReentrantLockGuard<'_, T> {}
216
217#[unstable(feature = "reentrant_lock", issue = "121440")]
218impl<T> ReentrantLock<T> {
219    /// Creates a new re-entrant lock in an unlocked state ready for use.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// #![feature(reentrant_lock)]
225    /// use std::sync::ReentrantLock;
226    ///
227    /// let lock = ReentrantLock::new(0);
228    /// ```
229    pub const fn new(t: T) -> ReentrantLock<T> {
230        ReentrantLock {
231            mutex: sys::Mutex::new(),
232            owner: Tid::new(),
233            lock_count: UnsafeCell::new(0),
234            data: t,
235        }
236    }
237
238    /// Consumes this lock, returning the underlying data.
239    ///
240    /// # Examples
241    ///
242    /// ```
243    /// #![feature(reentrant_lock)]
244    ///
245    /// use std::sync::ReentrantLock;
246    ///
247    /// let lock = ReentrantLock::new(0);
248    /// assert_eq!(lock.into_inner(), 0);
249    /// ```
250    pub fn into_inner(self) -> T {
251        self.data
252    }
253}
254
255#[unstable(feature = "reentrant_lock", issue = "121440")]
256impl<T: ?Sized> ReentrantLock<T> {
257    /// Acquires the lock, blocking the current thread until it is able to do
258    /// so.
259    ///
260    /// This function will block the caller until it is available to acquire
261    /// the lock. Upon returning, the thread is the only thread with the lock
262    /// held. When the thread calling this method already holds the lock, the
263    /// call succeeds without blocking.
264    ///
265    /// # Examples
266    ///
267    /// ```
268    /// #![feature(reentrant_lock)]
269    /// use std::cell::Cell;
270    /// use std::sync::{Arc, ReentrantLock};
271    /// use std::thread;
272    ///
273    /// let lock = Arc::new(ReentrantLock::new(Cell::new(0)));
274    /// let c_lock = Arc::clone(&lock);
275    ///
276    /// thread::spawn(move || {
277    ///     c_lock.lock().set(10);
278    /// }).join().expect("thread::spawn failed");
279    /// assert_eq!(lock.lock().get(), 10);
280    /// ```
281    pub fn lock(&self) -> ReentrantLockGuard<'_, T> {
282        let this_thread = current_id();
283        // Safety: We only touch lock_count when we own the inner mutex.
284        // Additionally, we only call `self.owner.set()` while holding
285        // the inner mutex, so no two threads can call it concurrently.
286        unsafe {
287            if self.owner.contains(this_thread) {
288                self.increment_lock_count().expect("lock count overflow in reentrant mutex");
289            } else {
290                self.mutex.lock();
291                self.owner.set(Some(this_thread));
292                debug_assert_eq!(*self.lock_count.get(), 0);
293                *self.lock_count.get() = 1;
294            }
295        }
296        ReentrantLockGuard { lock: self }
297    }
298
299    /// Returns a mutable reference to the underlying data.
300    ///
301    /// Since this call borrows the `ReentrantLock` mutably, no actual locking
302    /// needs to take place -- the mutable borrow statically guarantees no locks
303    /// exist.
304    ///
305    /// # Examples
306    ///
307    /// ```
308    /// #![feature(reentrant_lock)]
309    /// use std::sync::ReentrantLock;
310    ///
311    /// let mut lock = ReentrantLock::new(0);
312    /// *lock.get_mut() = 10;
313    /// assert_eq!(*lock.lock(), 10);
314    /// ```
315    pub fn get_mut(&mut self) -> &mut T {
316        &mut self.data
317    }
318
319    /// Attempts to acquire this lock.
320    ///
321    /// If the lock could not be acquired at this time, then `None` is returned.
322    /// Otherwise, an RAII guard is returned.
323    ///
324    /// This function does not block.
325    // FIXME maybe make it a public part of the API?
326    #[unstable(issue = "none", feature = "std_internals")]
327    #[doc(hidden)]
328    pub fn try_lock(&self) -> Option<ReentrantLockGuard<'_, T>> {
329        let this_thread = current_id();
330        // Safety: We only touch lock_count when we own the inner mutex.
331        // Additionally, we only call `self.owner.set()` while holding
332        // the inner mutex, so no two threads can call it concurrently.
333        unsafe {
334            if self.owner.contains(this_thread) {
335                self.increment_lock_count()?;
336                Some(ReentrantLockGuard { lock: self })
337            } else if self.mutex.try_lock() {
338                self.owner.set(Some(this_thread));
339                debug_assert_eq!(*self.lock_count.get(), 0);
340                *self.lock_count.get() = 1;
341                Some(ReentrantLockGuard { lock: self })
342            } else {
343                None
344            }
345        }
346    }
347
348    /// Returns a raw pointer to the underlying data.
349    ///
350    /// The returned pointer is always non-null and properly aligned, but it is
351    /// the user's responsibility to ensure that any reads through it are
352    /// properly synchronized to avoid data races, and that it is not read
353    /// through after the lock is dropped.
354    #[unstable(feature = "reentrant_lock_data_ptr", issue = "140368")]
355    pub const fn data_ptr(&self) -> *const T {
356        &raw const self.data
357    }
358
359    unsafe fn increment_lock_count(&self) -> Option<()> {
360        unsafe {
361            *self.lock_count.get() = (*self.lock_count.get()).checked_add(1)?;
362        }
363        Some(())
364    }
365}
366
367#[unstable(feature = "reentrant_lock", issue = "121440")]
368impl<T: fmt::Debug + ?Sized> fmt::Debug for ReentrantLock<T> {
369    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370        let mut d = f.debug_struct("ReentrantLock");
371        match self.try_lock() {
372            Some(v) => d.field("data", &&*v),
373            None => d.field("data", &format_args!("<locked>")),
374        };
375        d.finish_non_exhaustive()
376    }
377}
378
379#[unstable(feature = "reentrant_lock", issue = "121440")]
380impl<T: Default> Default for ReentrantLock<T> {
381    fn default() -> Self {
382        Self::new(T::default())
383    }
384}
385
386#[unstable(feature = "reentrant_lock", issue = "121440")]
387impl<T> From<T> for ReentrantLock<T> {
388    fn from(t: T) -> Self {
389        Self::new(t)
390    }
391}
392
393#[unstable(feature = "reentrant_lock", issue = "121440")]
394impl<T: ?Sized> Deref for ReentrantLockGuard<'_, T> {
395    type Target = T;
396
397    fn deref(&self) -> &T {
398        &self.lock.data
399    }
400}
401
402#[unstable(feature = "reentrant_lock", issue = "121440")]
403impl<T: fmt::Debug + ?Sized> fmt::Debug for ReentrantLockGuard<'_, T> {
404    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405        (**self).fmt(f)
406    }
407}
408
409#[unstable(feature = "reentrant_lock", issue = "121440")]
410impl<T: fmt::Display + ?Sized> fmt::Display for ReentrantLockGuard<'_, T> {
411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412        (**self).fmt(f)
413    }
414}
415
416#[unstable(feature = "reentrant_lock", issue = "121440")]
417impl<T: ?Sized> Drop for ReentrantLockGuard<'_, T> {
418    #[inline]
419    fn drop(&mut self) {
420        // Safety: We own the lock.
421        unsafe {
422            *self.lock.lock_count.get() -= 1;
423            if *self.lock.lock_count.get() == 0 {
424                self.lock.owner.set(None);
425                self.lock.mutex.unlock();
426            }
427        }
428    }
429}