1 //! This module defines types which are thread safe if cfg!(parallel_compiler) is true.
3 //! `Lrc` is an alias of `Arc` if cfg!(parallel_compiler) is true, `Rc` otherwise.
6 //! It internally uses `parking_lot::Mutex` if cfg!(parallel_compiler) is true,
7 //! `RefCell` otherwise.
9 //! `RwLock` is a read-write lock.
10 //! It internally uses `parking_lot::RwLock` if cfg!(parallel_compiler) is true,
11 //! `RefCell` otherwise.
13 //! `MTLock` is a mutex which disappears if cfg!(parallel_compiler) is false.
15 //! `MTRef` is an immutable reference if cfg!(parallel_compiler), and a mutable reference otherwise.
17 //! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send + Sync
18 //! depending on the value of cfg!(parallel_compiler).
20 use crate::owning_ref::{Erased, OwningRef};
21 use std::collections::HashMap;
22 use std::hash::{BuildHasher, Hash};
23 use std::marker::PhantomData;
24 use std::ops::{Deref, DerefMut};
26 pub use std::sync::atomic::Ordering;
27 pub use std::sync::atomic::Ordering::SeqCst;
30 if #[cfg(not(parallel_compiler))] {
31 pub auto trait Send {}
32 pub auto trait Sync {}
34 impl<T: ?Sized> Send for T {}
35 impl<T: ?Sized> Sync for T {}
38 macro_rules! rustc_erase_owner {
45 use std::panic::{resume_unwind, catch_unwind, AssertUnwindSafe};
47 /// This is a single threaded variant of AtomicCell provided by crossbeam.
48 /// Unlike `Atomic` this is intended for all `Copy` types,
49 /// but it lacks the explicit ordering arguments.
51 pub struct AtomicCell<T: Copy>(Cell<T>);
53 impl<T: Copy> AtomicCell<T> {
55 pub fn new(v: T) -> Self {
56 AtomicCell(Cell::new(v))
60 pub fn get_mut(&mut self) -> &mut T {
65 impl<T: Copy> AtomicCell<T> {
67 pub fn into_inner(self) -> T {
72 pub fn load(&self) -> T {
77 pub fn store(&self, val: T) {
82 pub fn swap(&self, val: T) -> T {
87 /// This is a single threaded variant of `AtomicU64`, `AtomicUsize`, etc.
88 /// It differs from `AtomicCell` in that it has explicit ordering arguments
89 /// and is only intended for use with the native atomic types.
90 /// You should use this type through the `AtomicU64`, `AtomicUsize`, etc, type aliases
91 /// as it's not intended to be used separately.
93 pub struct Atomic<T: Copy>(Cell<T>);
95 impl<T: Copy> Atomic<T> {
97 pub fn new(v: T) -> Self {
102 impl<T: Copy> Atomic<T> {
104 pub fn into_inner(self) -> T {
109 pub fn load(&self, _: Ordering) -> T {
114 pub fn store(&self, val: T, _: Ordering) {
119 pub fn swap(&self, val: T, _: Ordering) -> T {
124 impl<T: Copy + PartialEq> Atomic<T> {
126 pub fn compare_exchange(&self,
132 let read = self.0.get();
142 impl<T: Add<Output=T> + Copy> Atomic<T> {
144 pub fn fetch_add(&self, val: T, _: Ordering) -> T {
145 let old = self.0.get();
146 self.0.set(old + val);
151 pub type AtomicUsize = Atomic<usize>;
152 pub type AtomicBool = Atomic<bool>;
153 pub type AtomicU32 = Atomic<u32>;
154 pub type AtomicU64 = Atomic<u64>;
156 pub fn join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
157 where A: FnOnce() -> RA,
163 pub struct SerialScope;
166 pub fn spawn<F>(&self, f: F)
167 where F: FnOnce(&SerialScope)
173 pub fn scope<F, R>(f: F) -> R
174 where F: FnOnce(&SerialScope) -> R
180 macro_rules! parallel {
181 ($($blocks:tt),*) => {
182 // We catch panics here ensuring that all the blocks execute.
183 // This makes behavior consistent with the parallel compiler.
184 let mut panic = None;
186 if let Err(p) = ::std::panic::catch_unwind(
187 ::std::panic::AssertUnwindSafe(|| $blocks)
194 if let Some(panic) = panic {
195 ::std::panic::resume_unwind(panic);
200 pub use std::iter::Iterator as ParallelIterator;
202 pub fn par_iter<T: IntoIterator>(t: T) -> T::IntoIter {
206 pub fn par_for_each_in<T: IntoIterator>(
209 impl Fn(<<T as IntoIterator>::IntoIter as Iterator>::Item) + Sync + Send
211 // We catch panics here ensuring that all the loop iterations execute.
212 // This makes behavior consistent with the parallel compiler.
213 let mut panic = None;
214 t.into_iter().for_each(|i| {
215 if let Err(p) = catch_unwind(AssertUnwindSafe(|| for_each(i))) {
221 if let Some(panic) = panic {
222 resume_unwind(panic);
226 pub type MetadataRef = OwningRef<Box<dyn Erased>, [u8]>;
228 pub use std::rc::Rc as Lrc;
229 pub use std::rc::Weak as Weak;
230 pub use std::cell::Ref as ReadGuard;
231 pub use std::cell::Ref as MappedReadGuard;
232 pub use std::cell::RefMut as WriteGuard;
233 pub use std::cell::RefMut as MappedWriteGuard;
234 pub use std::cell::RefMut as LockGuard;
235 pub use std::cell::RefMut as MappedLockGuard;
237 use std::cell::RefCell as InnerRwLock;
238 use std::cell::RefCell as InnerLock;
243 pub struct WorkerLocal<T>(OneThread<T>);
245 impl<T> WorkerLocal<T> {
246 /// Creates a new worker local where the `initial` closure computes the
247 /// value this worker local should take for each thread in the thread pool.
249 pub fn new<F: FnMut(usize) -> T>(mut f: F) -> WorkerLocal<T> {
250 WorkerLocal(OneThread::new(f(0)))
253 /// Returns the worker-local value for each thread
255 pub fn into_inner(self) -> Vec<T> {
256 vec![OneThread::into_inner(self.0)]
260 impl<T> Deref for WorkerLocal<T> {
264 fn deref(&self) -> &T {
269 pub type MTRef<'a, T> = &'a mut T;
271 #[derive(Debug, Default)]
272 pub struct MTLock<T>(T);
276 pub fn new(inner: T) -> Self {
281 pub fn into_inner(self) -> T {
286 pub fn get_mut(&mut self) -> &mut T {
291 pub fn lock(&self) -> &T {
296 pub fn lock_mut(&mut self) -> &mut T {
301 // FIXME: Probably a bad idea (in the threaded case)
302 impl<T: Clone> Clone for MTLock<T> {
304 fn clone(&self) -> Self {
305 MTLock(self.0.clone())
309 pub use std::marker::Send as Send;
310 pub use std::marker::Sync as Sync;
312 pub use parking_lot::RwLockReadGuard as ReadGuard;
313 pub use parking_lot::MappedRwLockReadGuard as MappedReadGuard;
314 pub use parking_lot::RwLockWriteGuard as WriteGuard;
315 pub use parking_lot::MappedRwLockWriteGuard as MappedWriteGuard;
317 pub use parking_lot::MutexGuard as LockGuard;
318 pub use parking_lot::MappedMutexGuard as MappedLockGuard;
320 pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32, AtomicU64};
322 pub use crossbeam_utils::atomic::AtomicCell;
324 pub use std::sync::Arc as Lrc;
325 pub use std::sync::Weak as Weak;
327 pub type MTRef<'a, T> = &'a T;
329 #[derive(Debug, Default)]
330 pub struct MTLock<T>(Lock<T>);
334 pub fn new(inner: T) -> Self {
335 MTLock(Lock::new(inner))
339 pub fn into_inner(self) -> T {
344 pub fn get_mut(&mut self) -> &mut T {
349 pub fn lock(&self) -> LockGuard<'_, T> {
354 pub fn lock_mut(&self) -> LockGuard<'_, T> {
359 use parking_lot::Mutex as InnerLock;
360 use parking_lot::RwLock as InnerRwLock;
364 pub use rayon::{join, scope};
366 /// Runs a list of blocks in parallel. The first block is executed immediately on
367 /// the current thread. Use that for the longest running block.
369 macro_rules! parallel {
370 (impl $fblock:tt [$($c:tt,)*] [$block:tt $(, $rest:tt)*]) => {
371 parallel!(impl $fblock [$block, $($c,)*] [$($rest),*])
373 (impl $fblock:tt [$($blocks:tt,)*] []) => {
374 ::rustc_data_structures::sync::scope(|s| {
376 s.spawn(|_| $blocks);
381 ($fblock:tt, $($blocks:tt),*) => {
382 // Reverse the order of the later blocks since Rayon executes them in reverse order
383 // when using a single thread. This ensures the execution order matches that
384 // of a single threaded rustc
385 parallel!(impl $fblock [] [$($blocks),*]);
389 pub use rayon_core::WorkerLocal;
391 pub use rayon::iter::ParallelIterator;
392 use rayon::iter::IntoParallelIterator;
394 pub fn par_iter<T: IntoParallelIterator>(t: T) -> T::Iter {
398 pub fn par_for_each_in<T: IntoParallelIterator>(
401 <<T as IntoParallelIterator>::Iter as ParallelIterator>::Item
404 t.into_par_iter().for_each(for_each)
407 pub type MetadataRef = OwningRef<Box<dyn Erased + Send + Sync>, [u8]>;
409 /// This makes locks panic if they are already held.
410 /// It is only useful when you are running in a single thread
411 const ERROR_CHECKING: bool = false;
414 macro_rules! rustc_erase_owner {
417 ::rustc_data_structures::sync::assert_send_val(&v);
418 v.erase_send_sync_owner()
424 pub fn assert_sync<T: ?Sized + Sync>() {}
425 pub fn assert_send<T: ?Sized + Send>() {}
426 pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
427 pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}
429 pub trait HashMapExt<K, V> {
430 /// Same as HashMap::insert, but it may panic if there's already an
431 /// entry for `key` with a value not equal to `value`
432 fn insert_same(&mut self, key: K, value: V);
435 impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
436 fn insert_same(&mut self, key: K, value: V) {
437 self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
441 /// A type whose inner value can be written once and then will stay read-only
442 // This contains a PhantomData<T> since this type conceptually owns a T outside the Mutex once
443 // initialized. This ensures that Once<T> is Sync only if T is. If we did not have PhantomData<T>
444 // we could send a &Once<Cell<bool>> to multiple threads and call `get` on it to get access
445 // to &Cell<bool> on those threads.
446 pub struct Once<T>(Lock<Option<T>>, PhantomData<T>);
449 /// Creates an Once value which is uninitialized
451 pub fn new() -> Self {
452 Once(Lock::new(None), PhantomData)
455 /// Consumes the value and returns Some(T) if it was initialized
457 pub fn into_inner(self) -> Option<T> {
461 /// Tries to initialize the inner value to `value`.
462 /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
463 /// otherwise if the inner value was already set it returns `value` back to the caller
465 pub fn try_set(&self, value: T) -> Option<T> {
466 let mut lock = self.0.lock();
474 /// Tries to initialize the inner value to `value`.
475 /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
476 /// otherwise if the inner value was already set it asserts that `value` is equal to the inner
477 /// value and then returns `value` back to the caller
479 pub fn try_set_same(&self, value: T) -> Option<T>
483 let mut lock = self.0.lock();
484 if let Some(ref inner) = *lock {
485 assert!(*inner == value);
492 /// Tries to initialize the inner value to `value` and panics if it was already initialized
494 pub fn set(&self, value: T) {
495 assert!(self.try_set(value).is_none());
498 /// Initializes the inner value if it wasn't already done by calling the provided closure. It
499 /// ensures that no-one else can access the value in the mean time by holding a lock for the
500 /// duration of the closure.
501 /// A reference to the inner value is returned.
503 pub fn init_locking<F: FnOnce() -> T>(&self, f: F) -> &T {
505 let mut lock = self.0.lock();
514 /// Tries to initialize the inner value by calling the closure without ensuring that no-one
515 /// else can access it. This mean when this is called from multiple threads, multiple
516 /// closures may concurrently be computing a value which the inner value should take.
517 /// Only one of these closures are used to actually initialize the value.
518 /// If some other closure already set the value,
519 /// we return the value our closure computed wrapped in a `Option`.
520 /// If our closure set the value, `None` is returned.
521 /// If the value is already initialized, the closure is not called and `None` is returned.
523 pub fn init_nonlocking<F: FnOnce() -> T>(&self, f: F) -> Option<T> {
524 if self.0.lock().is_some() { None } else { self.try_set(f()) }
527 /// Tries to initialize the inner value by calling the closure without ensuring that no-one
528 /// else can access it. This mean when this is called from multiple threads, multiple
529 /// closures may concurrently be computing a value which the inner value should take.
530 /// Only one of these closures are used to actually initialize the value.
531 /// If some other closure already set the value, we assert that it our closure computed
532 /// a value equal to the value already set and then
533 /// we return the value our closure computed wrapped in a `Option`.
534 /// If our closure set the value, `None` is returned.
535 /// If the value is already initialized, the closure is not called and `None` is returned.
537 pub fn init_nonlocking_same<F: FnOnce() -> T>(&self, f: F) -> Option<T>
541 if self.0.lock().is_some() { None } else { self.try_set_same(f()) }
544 /// Tries to get a reference to the inner value, returns `None` if it is not yet initialized
546 pub fn try_get(&self) -> Option<&T> {
547 let lock = &*self.0.lock();
548 if let Some(ref inner) = *lock {
549 // This is safe since we won't mutate the inner value
550 unsafe { Some(&*(inner as *const T)) }
556 /// Gets reference to the inner value, panics if it is not yet initialized
558 pub fn get(&self) -> &T {
559 self.try_get().expect("value was not set")
562 /// Gets reference to the inner value, panics if it is not yet initialized
564 pub fn borrow(&self) -> &T {
570 pub struct Lock<T>(InnerLock<T>);
574 pub fn new(inner: T) -> Self {
575 Lock(InnerLock::new(inner))
579 pub fn into_inner(self) -> T {
584 pub fn get_mut(&mut self) -> &mut T {
588 #[cfg(parallel_compiler)]
590 pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
594 #[cfg(not(parallel_compiler))]
596 pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
597 self.0.try_borrow_mut().ok()
600 #[cfg(parallel_compiler)]
602 pub fn lock(&self) -> LockGuard<'_, T> {
604 self.0.try_lock().expect("lock was already held")
610 #[cfg(not(parallel_compiler))]
612 pub fn lock(&self) -> LockGuard<'_, T> {
617 pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
622 pub fn borrow(&self) -> LockGuard<'_, T> {
627 pub fn borrow_mut(&self) -> LockGuard<'_, T> {
632 impl<T: Default> Default for Lock<T> {
634 fn default() -> Self {
635 Lock::new(T::default())
639 // FIXME: Probably a bad idea
640 impl<T: Clone> Clone for Lock<T> {
642 fn clone(&self) -> Self {
643 Lock::new(self.borrow().clone())
648 pub struct RwLock<T>(InnerRwLock<T>);
652 pub fn new(inner: T) -> Self {
653 RwLock(InnerRwLock::new(inner))
657 pub fn into_inner(self) -> T {
662 pub fn get_mut(&mut self) -> &mut T {
666 #[cfg(not(parallel_compiler))]
668 pub fn read(&self) -> ReadGuard<'_, T> {
672 #[cfg(parallel_compiler)]
674 pub fn read(&self) -> ReadGuard<'_, T> {
676 self.0.try_read().expect("lock was already held")
683 pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
687 #[cfg(not(parallel_compiler))]
689 pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
690 self.0.try_borrow_mut().map_err(|_| ())
693 #[cfg(parallel_compiler)]
695 pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
696 self.0.try_write().ok_or(())
699 #[cfg(not(parallel_compiler))]
701 pub fn write(&self) -> WriteGuard<'_, T> {
705 #[cfg(parallel_compiler)]
707 pub fn write(&self) -> WriteGuard<'_, T> {
709 self.0.try_write().expect("lock was already held")
716 pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
717 f(&mut *self.write())
721 pub fn borrow(&self) -> ReadGuard<'_, T> {
726 pub fn borrow_mut(&self) -> WriteGuard<'_, T> {
731 // FIXME: Probably a bad idea
732 impl<T: Clone> Clone for RwLock<T> {
734 fn clone(&self) -> Self {
735 RwLock::new(self.borrow().clone())
739 /// A type which only allows its inner value to be used in one thread.
740 /// It will panic if it is used on multiple threads.
742 pub struct OneThread<T> {
743 #[cfg(parallel_compiler)]
744 thread: thread::ThreadId,
748 #[cfg(parallel_compiler)]
749 unsafe impl<T> std::marker::Sync for OneThread<T> {}
750 #[cfg(parallel_compiler)]
751 unsafe impl<T> std::marker::Send for OneThread<T> {}
753 impl<T> OneThread<T> {
756 #[cfg(parallel_compiler)]
757 assert_eq!(thread::current().id(), self.thread);
761 pub fn new(inner: T) -> Self {
763 #[cfg(parallel_compiler)]
764 thread: thread::current().id(),
770 pub fn into_inner(value: Self) -> T {
776 impl<T> Deref for OneThread<T> {
779 fn deref(&self) -> &T {
785 impl<T> DerefMut for OneThread<T> {
786 fn deref_mut(&mut self) -> &mut T {