1 //! This module defines types which are thread safe if cfg!(parallel_compiler) is true.
3 //! `Lrc` is an alias of either Rc or Arc.
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 a immutable reference if cfg!(parallel_compiler), and an 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 std::collections::HashMap;
21 use std::hash::{Hash, BuildHasher};
22 use std::marker::PhantomData;
23 use std::ops::{Deref, DerefMut};
24 use crate::owning_ref::{Erased, OwningRef};
26 pub fn serial_join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
27 where A: FnOnce() -> RA,
33 pub struct SerialScope;
36 pub fn spawn<F>(&self, f: F)
37 where F: FnOnce(&SerialScope)
43 pub fn serial_scope<F, R>(f: F) -> R
44 where F: FnOnce(&SerialScope) -> R
49 pub use std::sync::atomic::Ordering::SeqCst;
50 pub use std::sync::atomic::Ordering;
53 if #[cfg(not(parallel_compiler))] {
54 pub auto trait Send {}
55 pub auto trait Sync {}
57 impl<T: ?Sized> Send for T {}
58 impl<T: ?Sized> Sync for T {}
61 macro_rules! rustc_erase_owner {
68 use std::panic::{resume_unwind, catch_unwind, AssertUnwindSafe};
71 pub struct Atomic<T: Copy>(Cell<T>);
73 impl<T: Copy> Atomic<T> {
75 pub fn new(v: T) -> Self {
80 impl<T: Copy + PartialEq> Atomic<T> {
81 pub fn into_inner(self) -> T {
86 pub fn load(&self, _: Ordering) -> T {
91 pub fn store(&self, val: T, _: Ordering) {
95 pub fn swap(&self, val: T, _: Ordering) -> T {
99 pub fn compare_exchange(&self,
105 let read = self.0.get();
115 impl<T: Add<Output=T> + Copy> Atomic<T> {
116 pub fn fetch_add(&self, val: T, _: Ordering) -> T {
117 let old = self.0.get();
118 self.0.set(old + val);
123 pub type AtomicUsize = Atomic<usize>;
124 pub type AtomicBool = Atomic<bool>;
125 pub type AtomicU32 = Atomic<u32>;
126 pub type AtomicU64 = Atomic<u64>;
128 pub use self::serial_join as join;
129 pub use self::serial_scope as scope;
132 macro_rules! parallel {
133 ($($blocks:tt),*) => {
134 // We catch panics here ensuring that all the blocks execute.
135 // This makes behavior consistent with the parallel compiler.
136 let mut panic = None;
138 if let Err(p) = ::std::panic::catch_unwind(
139 ::std::panic::AssertUnwindSafe(|| $blocks)
146 if let Some(panic) = panic {
147 ::std::panic::resume_unwind(panic);
152 pub use std::iter::Iterator as ParallelIterator;
154 pub fn par_iter<T: IntoIterator>(t: T) -> T::IntoIter {
158 pub fn par_for_each_in<T: IntoIterator>(
161 impl Fn(<<T as IntoIterator>::IntoIter as Iterator>::Item) + Sync + Send
163 // We catch panics here ensuring that all the loop iterations execute.
164 // This makes behavior consistent with the parallel compiler.
165 let mut panic = None;
166 t.into_iter().for_each(|i| {
167 if let Err(p) = catch_unwind(AssertUnwindSafe(|| for_each(i))) {
173 if let Some(panic) = panic {
174 resume_unwind(panic);
178 pub type MetadataRef = OwningRef<Box<dyn Erased>, [u8]>;
180 pub use std::rc::Rc as Lrc;
181 pub use std::rc::Weak as Weak;
182 pub use std::cell::Ref as ReadGuard;
183 pub use std::cell::Ref as MappedReadGuard;
184 pub use std::cell::RefMut as WriteGuard;
185 pub use std::cell::RefMut as MappedWriteGuard;
186 pub use std::cell::RefMut as LockGuard;
187 pub use std::cell::RefMut as MappedLockGuard;
189 use std::cell::RefCell as InnerRwLock;
190 use std::cell::RefCell as InnerLock;
195 pub struct WorkerLocal<T>(OneThread<T>);
197 impl<T> WorkerLocal<T> {
198 /// Creates a new worker local where the `initial` closure computes the
199 /// value this worker local should take for each thread in the thread pool.
201 pub fn new<F: FnMut(usize) -> T>(mut f: F) -> WorkerLocal<T> {
202 WorkerLocal(OneThread::new(f(0)))
205 /// Returns the worker-local value for each thread
207 pub fn into_inner(self) -> Vec<T> {
208 vec![OneThread::into_inner(self.0)]
212 impl<T> Deref for WorkerLocal<T> {
216 fn deref(&self) -> &T {
221 pub type MTRef<'a, T> = &'a mut T;
223 #[derive(Debug, Default)]
224 pub struct MTLock<T>(T);
228 pub fn new(inner: T) -> Self {
233 pub fn into_inner(self) -> T {
238 pub fn get_mut(&mut self) -> &mut T {
243 pub fn lock(&self) -> &T {
248 pub fn lock_mut(&mut self) -> &mut T {
253 // FIXME: Probably a bad idea (in the threaded case)
254 impl<T: Clone> Clone for MTLock<T> {
256 fn clone(&self) -> Self {
257 MTLock(self.0.clone())
261 pub use std::marker::Send as Send;
262 pub use std::marker::Sync as Sync;
264 pub use parking_lot::RwLockReadGuard as ReadGuard;
265 pub use parking_lot::MappedRwLockReadGuard as MappedReadGuard;
266 pub use parking_lot::RwLockWriteGuard as WriteGuard;
267 pub use parking_lot::MappedRwLockWriteGuard as MappedWriteGuard;
269 pub use parking_lot::MutexGuard as LockGuard;
270 pub use parking_lot::MappedMutexGuard as MappedLockGuard;
272 pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32, AtomicU64};
274 pub use std::sync::Arc as Lrc;
275 pub use std::sync::Weak as Weak;
277 pub type MTRef<'a, T> = &'a T;
279 #[derive(Debug, Default)]
280 pub struct MTLock<T>(Lock<T>);
284 pub fn new(inner: T) -> Self {
285 MTLock(Lock::new(inner))
289 pub fn into_inner(self) -> T {
294 pub fn get_mut(&mut self) -> &mut T {
299 pub fn lock(&self) -> LockGuard<'_, T> {
304 pub fn lock_mut(&self) -> LockGuard<'_, T> {
309 use parking_lot::Mutex as InnerLock;
310 use parking_lot::RwLock as InnerRwLock;
314 pub use rayon::{join, scope};
316 /// Runs a list of blocks in parallel. The first block is executed immediately on
317 /// the current thread. Use that for the longest running block.
319 macro_rules! parallel {
320 (impl $fblock:tt [$($c:tt,)*] [$block:tt $(, $rest:tt)*]) => {
321 parallel!(impl $fblock [$block, $($c,)*] [$($rest),*])
323 (impl $fblock:tt [$($blocks:tt,)*] []) => {
324 ::rustc_data_structures::sync::scope(|s| {
326 s.spawn(|_| $blocks);
331 ($fblock:tt, $($blocks:tt),*) => {
332 // Reverse the order of the later blocks since Rayon executes them in reverse order
333 // when using a single thread. This ensures the execution order matches that
334 // of a single threaded rustc
335 parallel!(impl $fblock [] [$($blocks),*]);
339 pub use rayon_core::WorkerLocal;
341 pub use rayon::iter::ParallelIterator;
342 use rayon::iter::IntoParallelIterator;
344 pub fn par_iter<T: IntoParallelIterator>(t: T) -> T::Iter {
348 pub fn par_for_each_in<T: IntoParallelIterator>(
351 <<T as IntoParallelIterator>::Iter as ParallelIterator>::Item
354 t.into_par_iter().for_each(for_each)
357 pub type MetadataRef = OwningRef<Box<dyn Erased + Send + Sync>, [u8]>;
359 /// This makes locks panic if they are already held.
360 /// It is only useful when you are running in a single thread
361 const ERROR_CHECKING: bool = false;
364 macro_rules! rustc_erase_owner {
367 ::rustc_data_structures::sync::assert_send_val(&v);
368 v.erase_send_sync_owner()
374 pub fn assert_sync<T: ?Sized + Sync>() {}
375 pub fn assert_send<T: ?Sized + Send>() {}
376 pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
377 pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}
379 pub trait HashMapExt<K, V> {
380 /// Same as HashMap::insert, but it may panic if there's already an
381 /// entry for `key` with a value not equal to `value`
382 fn insert_same(&mut self, key: K, value: V);
385 impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
386 fn insert_same(&mut self, key: K, value: V) {
387 self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
391 /// A type whose inner value can be written once and then will stay read-only
392 // This contains a PhantomData<T> since this type conceptually owns a T outside the Mutex once
393 // initialized. This ensures that Once<T> is Sync only if T is. If we did not have PhantomData<T>
394 // we could send a &Once<Cell<bool>> to multiple threads and call `get` on it to get access
395 // to &Cell<bool> on those threads.
396 pub struct Once<T>(Lock<Option<T>>, PhantomData<T>);
399 /// Creates an Once value which is uninitialized
401 pub fn new() -> Self {
402 Once(Lock::new(None), PhantomData)
405 /// Consumes the value and returns Some(T) if it was initialized
407 pub fn into_inner(self) -> Option<T> {
411 /// Tries to initialize the inner value to `value`.
412 /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
413 /// otherwise if the inner value was already set it returns `value` back to the caller
415 pub fn try_set(&self, value: T) -> Option<T> {
416 let mut lock = self.0.lock();
424 /// Tries to initialize the inner value to `value`.
425 /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
426 /// otherwise if the inner value was already set it asserts that `value` is equal to the inner
427 /// value and then returns `value` back to the caller
429 pub fn try_set_same(&self, value: T) -> Option<T> where T: Eq {
430 let mut lock = self.0.lock();
431 if let Some(ref inner) = *lock {
432 assert!(*inner == value);
439 /// Tries to initialize the inner value to `value` and panics if it was already initialized
441 pub fn set(&self, value: T) {
442 assert!(self.try_set(value).is_none());
445 /// Tries to initialize the inner value by calling the closure while ensuring that no-one else
446 /// can access the value in the mean time by holding a lock for the duration of the closure.
447 /// If the value was already initialized the closure is not called and `false` is returned,
448 /// otherwise if the value from the closure initializes the inner value, `true` is returned
450 pub fn init_locking<F: FnOnce() -> T>(&self, f: F) -> bool {
451 let mut lock = self.0.lock();
459 /// Tries to initialize the inner value by calling the closure without ensuring that no-one
460 /// else can access it. This mean when this is called from multiple threads, multiple
461 /// closures may concurrently be computing a value which the inner value should take.
462 /// Only one of these closures are used to actually initialize the value.
463 /// If some other closure already set the value,
464 /// we return the value our closure computed wrapped in a `Option`.
465 /// If our closure set the value, `None` is returned.
466 /// If the value is already initialized, the closure is not called and `None` is returned.
468 pub fn init_nonlocking<F: FnOnce() -> T>(&self, f: F) -> Option<T> {
469 if self.0.lock().is_some() {
476 /// Tries to initialize the inner value by calling the closure without ensuring that no-one
477 /// else can access it. This mean when this is called from multiple threads, multiple
478 /// closures may concurrently be computing a value which the inner value should take.
479 /// Only one of these closures are used to actually initialize the value.
480 /// If some other closure already set the value, we assert that it our closure computed
481 /// a value equal to the value already set and then
482 /// we return the value our closure computed wrapped in a `Option`.
483 /// If our closure set the value, `None` is returned.
484 /// If the value is already initialized, the closure is not called and `None` is returned.
486 pub fn init_nonlocking_same<F: FnOnce() -> T>(&self, f: F) -> Option<T> where T: Eq {
487 if self.0.lock().is_some() {
490 self.try_set_same(f())
494 /// Tries to get a reference to the inner value, returns `None` if it is not yet initialized
496 pub fn try_get(&self) -> Option<&T> {
497 let lock = &*self.0.lock();
498 if let Some(ref inner) = *lock {
499 // This is safe since we won't mutate the inner value
500 unsafe { Some(&*(inner as *const T)) }
506 /// Gets reference to the inner value, panics if it is not yet initialized
508 pub fn get(&self) -> &T {
509 self.try_get().expect("value was not set")
512 /// Gets reference to the inner value, panics if it is not yet initialized
514 pub fn borrow(&self) -> &T {
520 pub struct Lock<T>(InnerLock<T>);
524 pub fn new(inner: T) -> Self {
525 Lock(InnerLock::new(inner))
529 pub fn into_inner(self) -> T {
534 pub fn get_mut(&mut self) -> &mut T {
538 #[cfg(parallel_compiler)]
540 pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
544 #[cfg(not(parallel_compiler))]
546 pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
547 self.0.try_borrow_mut().ok()
550 #[cfg(parallel_compiler)]
552 pub fn lock(&self) -> LockGuard<'_, T> {
554 self.0.try_lock().expect("lock was already held")
560 #[cfg(not(parallel_compiler))]
562 pub fn lock(&self) -> LockGuard<'_, T> {
567 pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
572 pub fn borrow(&self) -> LockGuard<'_, T> {
577 pub fn borrow_mut(&self) -> LockGuard<'_, T> {
582 impl<T: Default> Default for Lock<T> {
584 fn default() -> Self {
585 Lock::new(T::default())
589 // FIXME: Probably a bad idea
590 impl<T: Clone> Clone for Lock<T> {
592 fn clone(&self) -> Self {
593 Lock::new(self.borrow().clone())
598 pub struct RwLock<T>(InnerRwLock<T>);
602 pub fn new(inner: T) -> Self {
603 RwLock(InnerRwLock::new(inner))
607 pub fn into_inner(self) -> T {
612 pub fn get_mut(&mut self) -> &mut T {
616 #[cfg(not(parallel_compiler))]
618 pub fn read(&self) -> ReadGuard<'_, T> {
622 #[cfg(parallel_compiler)]
624 pub fn read(&self) -> ReadGuard<'_, T> {
626 self.0.try_read().expect("lock was already held")
633 pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
637 #[cfg(not(parallel_compiler))]
639 pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
640 self.0.try_borrow_mut().map_err(|_| ())
643 #[cfg(parallel_compiler)]
645 pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
646 self.0.try_write().ok_or(())
649 #[cfg(not(parallel_compiler))]
651 pub fn write(&self) -> WriteGuard<'_, T> {
655 #[cfg(parallel_compiler)]
657 pub fn write(&self) -> WriteGuard<'_, T> {
659 self.0.try_write().expect("lock was already held")
666 pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
667 f(&mut *self.write())
671 pub fn borrow(&self) -> ReadGuard<'_, T> {
676 pub fn borrow_mut(&self) -> WriteGuard<'_, T> {
681 // FIXME: Probably a bad idea
682 impl<T: Clone> Clone for RwLock<T> {
684 fn clone(&self) -> Self {
685 RwLock::new(self.borrow().clone())
689 /// A type which only allows its inner value to be used in one thread.
690 /// It will panic if it is used on multiple threads.
691 #[derive(Copy, Clone, Hash, Debug, Eq, PartialEq)]
692 pub struct OneThread<T> {
693 #[cfg(parallel_compiler)]
694 thread: thread::ThreadId,
698 #[cfg(parallel_compiler)]
699 unsafe impl<T> std::marker::Sync for OneThread<T> {}
700 #[cfg(parallel_compiler)]
701 unsafe impl<T> std::marker::Send for OneThread<T> {}
703 impl<T> OneThread<T> {
706 #[cfg(parallel_compiler)]
707 assert_eq!(thread::current().id(), self.thread);
711 pub fn new(inner: T) -> Self {
713 #[cfg(parallel_compiler)]
714 thread: thread::current().id(),
720 pub fn into_inner(value: Self) -> T {
726 impl<T> Deref for OneThread<T> {
729 fn deref(&self) -> &T {
735 impl<T> DerefMut for OneThread<T> {
736 fn deref_mut(&mut self) -> &mut T {