std/sync/
reentrant_lock.rs

1use cfg_if::cfg_if;
2
3use crate::cell::UnsafeCell;
4use crate::fmt;
5use crate::ops::Deref;
6use crate::panic::{RefUnwindSafe, UnwindSafe};
7use crate::sys::sync as sys;
8use crate::thread::{ThreadId, current_id};
9
10/// A re-entrant mutual exclusion lock
11///
12/// This lock will block *other* threads waiting for the lock to become
13/// available. The thread which has already locked the mutex can lock it
14/// multiple times without blocking, preventing a common source of deadlocks.
15///
16/// # Examples
17///
18/// Allow recursively calling a function needing synchronization from within
19/// a callback (this is how [`StdoutLock`](crate::io::StdoutLock) is currently
20/// implemented):
21///
22/// ```
23/// #![feature(reentrant_lock)]
24///
25/// use std::cell::RefCell;
26/// use std::sync::ReentrantLock;
27///
28/// pub struct Log {
29///     data: RefCell<String>,
30/// }
31///
32/// impl Log {
33///     pub fn append(&self, msg: &str) {
34///         self.data.borrow_mut().push_str(msg);
35///     }
36/// }
37///
38/// static LOG: ReentrantLock<Log> = ReentrantLock::new(Log { data: RefCell::new(String::new()) });
39///
40/// pub fn with_log<R>(f: impl FnOnce(&Log) -> R) -> R {
41///     let log = LOG.lock();
42///     f(&*log)
43/// }
44///
45/// with_log(|log| {
46///     log.append("Hello");
47///     with_log(|log| log.append(" there!"));
48/// });
49/// ```
50///
51// # Implementation details
52//
53// The 'owner' field tracks which thread has locked the mutex.
54//
55// We use thread::current_id() as the thread identifier, which is just the
56// current thread's ThreadId, so it's unique across the process lifetime.
57//
58// If `owner` is set to the identifier of the current thread,
59// we assume the mutex is already locked and instead of locking it again,
60// we increment `lock_count`.
61//
62// When unlocking, we decrement `lock_count`, and only unlock the mutex when
63// it reaches zero.
64//
65// `lock_count` is protected by the mutex and only accessed by the thread that has
66// locked the mutex, so needs no synchronization.
67//
68// `owner` can be checked by other threads that want to see if they already
69// hold the lock, so needs to be atomic. If it compares equal, we're on the
70// same thread that holds the mutex and memory access can use relaxed ordering
71// since we're not dealing with multiple threads. If it's not equal,
72// synchronization is left to the mutex, making relaxed memory ordering for
73// the `owner` field fine in all cases.
74//
75// On systems without 64 bit atomics we also store the address of a TLS variable
76// along the 64-bit TID. We then first check that address against the address
77// of that variable on the current thread, and only if they compare equal do we
78// compare the actual TIDs. Because we only ever read the TID on the same thread
79// that it was written on (or a thread sharing the TLS block with that writer thread),
80// we don't need to further synchronize the TID accesses, so they can be regular 64-bit
81// non-atomic accesses.
82#[unstable(feature = "reentrant_lock", issue = "121440")]
83pub struct ReentrantLock<T: ?Sized> {
84    mutex: sys::Mutex,
85    owner: Tid,
86    lock_count: UnsafeCell<u32>,
87    data: T,
88}
89
90cfg_if!(
91    if #[cfg(target_has_atomic = "64")] {
92        use crate::sync::atomic::{Atomic, AtomicU64, Ordering::Relaxed};
93
94        struct Tid(Atomic<u64>);
95
96        impl Tid {
97            const fn new() -> Self {
98                Self(AtomicU64::new(0))
99            }
100
101            #[inline]
102            fn contains(&self, owner: ThreadId) -> bool {
103                owner.as_u64().get() == self.0.load(Relaxed)
104            }
105
106            #[inline]
107            // This is just unsafe to match the API of the Tid type below.
108            unsafe fn set(&self, tid: Option<ThreadId>) {
109                let value = tid.map_or(0, |tid| tid.as_u64().get());
110                self.0.store(value, Relaxed);
111            }
112        }
113    } else {
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::{
123            Atomic,
124            AtomicUsize,
125            Ordering,
126        };
127
128        struct Tid {
129            // When a thread calls `set()`, this value gets updated to
130            // the address of a thread local on that thread. This is
131            // used as a first check in `contains()`; if the `tls_addr`
132            // doesn't match the TLS address of the current thread, then
133            // the ThreadId also can't match. Only if the TLS addresses do
134            // match do we read out the actual TID.
135            // Note also that we can use relaxed atomic operations here, because
136            // we only ever read from the tid if `tls_addr` matches the current
137            // TLS address. In that case, either the tid has been set by
138            // the current thread, or by a thread that has terminated before
139            // the current thread was created. In either case, no further
140            // synchronization is needed (as per <http://github.com/rust-lang/miri/issues/3450>)
141            tls_addr: Atomic<usize>,
142            tid: UnsafeCell<u64>,
143        }
144
145        unsafe impl Send for Tid {}
146        unsafe impl Sync for Tid {}
147
148        impl Tid {
149            const fn new() -> Self {
150                Self { tls_addr: AtomicUsize::new(0), tid: UnsafeCell::new(0) }
151            }
152
153            #[inline]
154            // NOTE: This assumes that `owner` is the ID of the current
155            // thread, and may spuriously return `false` if that's not the case.
156            fn contains(&self, owner: ThreadId) -> bool {
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    unsafe fn increment_lock_count(&self) -> Option<()> {
349        unsafe {
350            *self.lock_count.get() = (*self.lock_count.get()).checked_add(1)?;
351        }
352        Some(())
353    }
354}
355
356#[unstable(feature = "reentrant_lock", issue = "121440")]
357impl<T: fmt::Debug + ?Sized> fmt::Debug for ReentrantLock<T> {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        let mut d = f.debug_struct("ReentrantLock");
360        match self.try_lock() {
361            Some(v) => d.field("data", &&*v),
362            None => d.field("data", &format_args!("<locked>")),
363        };
364        d.finish_non_exhaustive()
365    }
366}
367
368#[unstable(feature = "reentrant_lock", issue = "121440")]
369impl<T: Default> Default for ReentrantLock<T> {
370    fn default() -> Self {
371        Self::new(T::default())
372    }
373}
374
375#[unstable(feature = "reentrant_lock", issue = "121440")]
376impl<T> From<T> for ReentrantLock<T> {
377    fn from(t: T) -> Self {
378        Self::new(t)
379    }
380}
381
382#[unstable(feature = "reentrant_lock", issue = "121440")]
383impl<T: ?Sized> Deref for ReentrantLockGuard<'_, T> {
384    type Target = T;
385
386    fn deref(&self) -> &T {
387        &self.lock.data
388    }
389}
390
391#[unstable(feature = "reentrant_lock", issue = "121440")]
392impl<T: fmt::Debug + ?Sized> fmt::Debug for ReentrantLockGuard<'_, T> {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        (**self).fmt(f)
395    }
396}
397
398#[unstable(feature = "reentrant_lock", issue = "121440")]
399impl<T: fmt::Display + ?Sized> fmt::Display for ReentrantLockGuard<'_, T> {
400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401        (**self).fmt(f)
402    }
403}
404
405#[unstable(feature = "reentrant_lock", issue = "121440")]
406impl<T: ?Sized> Drop for ReentrantLockGuard<'_, T> {
407    #[inline]
408    fn drop(&mut self) {
409        // Safety: We own the lock.
410        unsafe {
411            *self.lock.lock_count.get() -= 1;
412            if *self.lock.lock_count.get() == 0 {
413                self.lock.owner.set(None);
414                self.lock.mutex.unlock();
415            }
416        }
417    }
418}