]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/sync.rs
Auto merge of #53830 - davidtwco:issue-53228, r=nikomatsakis
[rust.git] / src / librustc_data_structures / sync.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This module defines types which are thread safe if cfg!(parallel_queries) is true.
12 //!
13 //! `Lrc` is an alias of either Rc or Arc.
14 //!
15 //! `Lock` is a mutex.
16 //! It internally uses `parking_lot::Mutex` if cfg!(parallel_queries) is true,
17 //! `RefCell` otherwise.
18 //!
19 //! `RwLock` is a read-write lock.
20 //! It internally uses `parking_lot::RwLock` if cfg!(parallel_queries) is true,
21 //! `RefCell` otherwise.
22 //!
23 //! `LockCell` is a thread safe version of `Cell`, with `set` and `get` operations.
24 //! It can never deadlock. It uses `Cell` when
25 //! cfg!(parallel_queries) is false, otherwise it is a `Lock`.
26 //!
27 //! `MTLock` is a mutex which disappears if cfg!(parallel_queries) is false.
28 //!
29 //! `MTRef` is a immutable reference if cfg!(parallel_queries), and an mutable reference otherwise.
30 //!
31 //! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send + Sync
32 //! depending on the value of cfg!(parallel_queries).
33
34 use std::collections::HashMap;
35 use std::hash::{Hash, BuildHasher};
36 use std::cmp::Ordering;
37 use std::marker::PhantomData;
38 use std::fmt::Debug;
39 use std::fmt::Formatter;
40 use std::fmt;
41 use std::ops::{Deref, DerefMut};
42 use owning_ref::{Erased, OwningRef};
43
44 pub fn serial_join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
45     where A: FnOnce() -> RA,
46           B: FnOnce() -> RB
47 {
48     (oper_a(), oper_b())
49 }
50
51 pub struct SerialScope;
52
53 impl SerialScope {
54     pub fn spawn<F>(&self, f: F)
55         where F: FnOnce(&SerialScope)
56     {
57         f(self)
58     }
59 }
60
61 pub fn serial_scope<F, R>(f: F) -> R
62     where F: FnOnce(&SerialScope) -> R
63 {
64     f(&SerialScope)
65 }
66
67 cfg_if! {
68     if #[cfg(not(parallel_queries))] {
69         pub auto trait Send {}
70         pub auto trait Sync {}
71
72         impl<T: ?Sized> Send for T {}
73         impl<T: ?Sized> Sync for T {}
74
75         #[macro_export]
76         macro_rules! rustc_erase_owner {
77             ($v:expr) => {
78                 $v.erase_owner()
79             }
80         }
81
82         pub use self::serial_join as join;
83         pub use self::serial_scope as scope;
84
85         pub use std::iter::Iterator as ParallelIterator;
86
87         pub fn par_iter<T: IntoIterator>(t: T) -> T::IntoIter {
88             t.into_iter()
89         }
90
91         pub type MetadataRef = OwningRef<Box<dyn Erased>, [u8]>;
92
93         pub use std::rc::Rc as Lrc;
94         pub use std::rc::Weak as Weak;
95         pub use std::cell::Ref as ReadGuard;
96         pub use std::cell::Ref as MappedReadGuard;
97         pub use std::cell::RefMut as WriteGuard;
98         pub use std::cell::RefMut as MappedWriteGuard;
99         pub use std::cell::RefMut as LockGuard;
100         pub use std::cell::RefMut as MappedLockGuard;
101
102         use std::cell::RefCell as InnerRwLock;
103         use std::cell::RefCell as InnerLock;
104
105         use std::cell::Cell;
106
107         #[derive(Debug)]
108         pub struct WorkerLocal<T>(OneThread<T>);
109
110         impl<T> WorkerLocal<T> {
111             /// Creates a new worker local where the `initial` closure computes the
112             /// value this worker local should take for each thread in the thread pool.
113             #[inline]
114             pub fn new<F: FnMut(usize) -> T>(mut f: F) -> WorkerLocal<T> {
115                 WorkerLocal(OneThread::new(f(0)))
116             }
117
118             /// Returns the worker-local value for each thread
119             #[inline]
120             pub fn into_inner(self) -> Vec<T> {
121                 vec![OneThread::into_inner(self.0)]
122             }
123         }
124
125         impl<T> Deref for WorkerLocal<T> {
126             type Target = T;
127
128             #[inline(always)]
129             fn deref(&self) -> &T {
130                 &*self.0
131             }
132         }
133
134         pub type MTRef<'a, T> = &'a mut T;
135
136         #[derive(Debug)]
137         pub struct MTLock<T>(T);
138
139         impl<T> MTLock<T> {
140             #[inline(always)]
141             pub fn new(inner: T) -> Self {
142                 MTLock(inner)
143             }
144
145             #[inline(always)]
146             pub fn into_inner(self) -> T {
147                 self.0
148             }
149
150             #[inline(always)]
151             pub fn get_mut(&mut self) -> &mut T {
152                 &mut self.0
153             }
154
155             #[inline(always)]
156             pub fn lock(&self) -> &T {
157                 &self.0
158             }
159
160             #[inline(always)]
161             pub fn lock_mut(&mut self) -> &mut T {
162                 &mut self.0
163             }
164         }
165
166         // FIXME: Probably a bad idea (in the threaded case)
167         impl<T: Clone> Clone for MTLock<T> {
168             #[inline]
169             fn clone(&self) -> Self {
170                 MTLock(self.0.clone())
171             }
172         }
173
174         pub struct LockCell<T>(Cell<T>);
175
176         impl<T> LockCell<T> {
177             #[inline(always)]
178             pub fn new(inner: T) -> Self {
179                 LockCell(Cell::new(inner))
180             }
181
182             #[inline(always)]
183             pub fn into_inner(self) -> T {
184                 self.0.into_inner()
185             }
186
187             #[inline(always)]
188             pub fn set(&self, new_inner: T) {
189                 self.0.set(new_inner);
190             }
191
192             #[inline(always)]
193             pub fn get(&self) -> T where T: Copy {
194                 self.0.get()
195             }
196
197             #[inline(always)]
198             pub fn set_mut(&mut self, new_inner: T) {
199                 self.0.set(new_inner);
200             }
201
202             #[inline(always)]
203             pub fn get_mut(&mut self) -> T where T: Copy {
204                 self.0.get()
205             }
206         }
207
208         impl<T> LockCell<Option<T>> {
209             #[inline(always)]
210             pub fn take(&self) -> Option<T> {
211                 unsafe { (*self.0.as_ptr()).take() }
212             }
213         }
214     } else {
215         pub use std::marker::Send as Send;
216         pub use std::marker::Sync as Sync;
217
218         pub use parking_lot::RwLockReadGuard as ReadGuard;
219         pub use parking_lot::MappedRwLockReadGuard as MappedReadGuard;
220         pub use parking_lot::RwLockWriteGuard as WriteGuard;
221         pub use parking_lot::MappedRwLockWriteGuard as MappedWriteGuard;
222
223         pub use parking_lot::MutexGuard as LockGuard;
224         pub use parking_lot::MappedMutexGuard as MappedLockGuard;
225
226         pub use std::sync::Arc as Lrc;
227         pub use std::sync::Weak as Weak;
228
229         pub type MTRef<'a, T> = &'a T;
230
231         #[derive(Debug)]
232         pub struct MTLock<T>(Lock<T>);
233
234         impl<T> MTLock<T> {
235             #[inline(always)]
236             pub fn new(inner: T) -> Self {
237                 MTLock(Lock::new(inner))
238             }
239
240             #[inline(always)]
241             pub fn into_inner(self) -> T {
242                 self.0.into_inner()
243             }
244
245             #[inline(always)]
246             pub fn get_mut(&mut self) -> &mut T {
247                 self.0.get_mut()
248             }
249
250             #[inline(always)]
251             pub fn lock(&self) -> LockGuard<T> {
252                 self.0.lock()
253             }
254
255             #[inline(always)]
256             pub fn lock_mut(&self) -> LockGuard<T> {
257                 self.lock()
258             }
259         }
260
261         use parking_lot::Mutex as InnerLock;
262         use parking_lot::RwLock as InnerRwLock;
263
264         use std;
265         use std::thread;
266         pub use rayon::{join, scope};
267
268         pub use rayon_core::WorkerLocal;
269
270         pub use rayon::iter::ParallelIterator;
271         use rayon::iter::IntoParallelIterator;
272
273         pub fn par_iter<T: IntoParallelIterator>(t: T) -> T::Iter {
274             t.into_par_iter()
275         }
276
277         pub type MetadataRef = OwningRef<Box<dyn Erased + Send + Sync>, [u8]>;
278
279         /// This makes locks panic if they are already held.
280         /// It is only useful when you are running in a single thread
281         const ERROR_CHECKING: bool = false;
282
283         #[macro_export]
284         macro_rules! rustc_erase_owner {
285             ($v:expr) => {{
286                 let v = $v;
287                 ::rustc_data_structures::sync::assert_send_val(&v);
288                 v.erase_send_sync_owner()
289             }}
290         }
291
292         pub struct LockCell<T>(Lock<T>);
293
294         impl<T> LockCell<T> {
295             #[inline(always)]
296             pub fn new(inner: T) -> Self {
297                 LockCell(Lock::new(inner))
298             }
299
300             #[inline(always)]
301             pub fn into_inner(self) -> T {
302                 self.0.into_inner()
303             }
304
305             #[inline(always)]
306             pub fn set(&self, new_inner: T) {
307                 *self.0.lock() = new_inner;
308             }
309
310             #[inline(always)]
311             pub fn get(&self) -> T where T: Copy {
312                 *self.0.lock()
313             }
314
315             #[inline(always)]
316             pub fn set_mut(&mut self, new_inner: T) {
317                 *self.0.get_mut() = new_inner;
318             }
319
320             #[inline(always)]
321             pub fn get_mut(&mut self) -> T where T: Copy {
322                 *self.0.get_mut()
323             }
324         }
325
326         impl<T> LockCell<Option<T>> {
327             #[inline(always)]
328             pub fn take(&self) -> Option<T> {
329                 self.0.lock().take()
330             }
331         }
332     }
333 }
334
335 pub fn assert_sync<T: ?Sized + Sync>() {}
336 pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
337 pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}
338
339 pub trait HashMapExt<K, V> {
340     /// Same as HashMap::insert, but it may panic if there's already an
341     /// entry for `key` with a value not equal to `value`
342     fn insert_same(&mut self, key: K, value: V);
343 }
344
345 impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
346     fn insert_same(&mut self, key: K, value: V) {
347         self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
348     }
349 }
350
351 /// A type whose inner value can be written once and then will stay read-only
352 // This contains a PhantomData<T> since this type conceptually owns a T outside the Mutex once
353 // initialized. This ensures that Once<T> is Sync only if T is. If we did not have PhantomData<T>
354 // we could send a &Once<Cell<bool>> to multiple threads and call `get` on it to get access
355 // to &Cell<bool> on those threads.
356 pub struct Once<T>(Lock<Option<T>>, PhantomData<T>);
357
358 impl<T> Once<T> {
359     /// Creates an Once value which is uninitialized
360     #[inline(always)]
361     pub fn new() -> Self {
362         Once(Lock::new(None), PhantomData)
363     }
364
365     /// Consumes the value and returns Some(T) if it was initialized
366     #[inline(always)]
367     pub fn into_inner(self) -> Option<T> {
368         self.0.into_inner()
369     }
370
371     /// Tries to initialize the inner value to `value`.
372     /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
373     /// otherwise if the inner value was already set it returns `value` back to the caller
374     #[inline]
375     pub fn try_set(&self, value: T) -> Option<T> {
376         let mut lock = self.0.lock();
377         if lock.is_some() {
378             return Some(value);
379         }
380         *lock = Some(value);
381         None
382     }
383
384     /// Tries to initialize the inner value to `value`.
385     /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
386     /// otherwise if the inner value was already set it asserts that `value` is equal to the inner
387     /// value and then returns `value` back to the caller
388     #[inline]
389     pub fn try_set_same(&self, value: T) -> Option<T> where T: Eq {
390         let mut lock = self.0.lock();
391         if let Some(ref inner) = *lock {
392             assert!(*inner == value);
393             return Some(value);
394         }
395         *lock = Some(value);
396         None
397     }
398
399     /// Tries to initialize the inner value to `value` and panics if it was already initialized
400     #[inline]
401     pub fn set(&self, value: T) {
402         assert!(self.try_set(value).is_none());
403     }
404
405     /// Tries to initialize the inner value by calling the closure while ensuring that no-one else
406     /// can access the value in the mean time by holding a lock for the duration of the closure.
407     /// If the value was already initialized the closure is not called and `false` is returned,
408     /// otherwise if the value from the closure initializes the inner value, `true` is returned
409     #[inline]
410     pub fn init_locking<F: FnOnce() -> T>(&self, f: F) -> bool {
411         let mut lock = self.0.lock();
412         if lock.is_some() {
413             return false;
414         }
415         *lock = Some(f());
416         true
417     }
418
419     /// Tries to initialize the inner value by calling the closure without ensuring that no-one
420     /// else can access it. This mean when this is called from multiple threads, multiple
421     /// closures may concurrently be computing a value which the inner value should take.
422     /// Only one of these closures are used to actually initialize the value.
423     /// If some other closure already set the value,
424     /// we return the value our closure computed wrapped in a `Option`.
425     /// If our closure set the value, `None` is returned.
426     /// If the value is already initialized, the closure is not called and `None` is returned.
427     #[inline]
428     pub fn init_nonlocking<F: FnOnce() -> T>(&self, f: F) -> Option<T> {
429         if self.0.lock().is_some() {
430             None
431         } else {
432             self.try_set(f())
433         }
434     }
435
436     /// Tries to initialize the inner value by calling the closure without ensuring that no-one
437     /// else can access it. This mean when this is called from multiple threads, multiple
438     /// closures may concurrently be computing a value which the inner value should take.
439     /// Only one of these closures are used to actually initialize the value.
440     /// If some other closure already set the value, we assert that it our closure computed
441     /// a value equal to the value already set and then
442     /// we return the value our closure computed wrapped in a `Option`.
443     /// If our closure set the value, `None` is returned.
444     /// If the value is already initialized, the closure is not called and `None` is returned.
445     #[inline]
446     pub fn init_nonlocking_same<F: FnOnce() -> T>(&self, f: F) -> Option<T> where T: Eq {
447         if self.0.lock().is_some() {
448             None
449         } else {
450             self.try_set_same(f())
451         }
452     }
453
454     /// Tries to get a reference to the inner value, returns `None` if it is not yet initialized
455     #[inline(always)]
456     pub fn try_get(&self) -> Option<&T> {
457         let lock = &*self.0.lock();
458         if let Some(ref inner) = *lock {
459             // This is safe since we won't mutate the inner value
460             unsafe { Some(&*(inner as *const T)) }
461         } else {
462             None
463         }
464     }
465
466     /// Gets reference to the inner value, panics if it is not yet initialized
467     #[inline(always)]
468     pub fn get(&self) -> &T {
469         self.try_get().expect("value was not set")
470     }
471
472     /// Gets reference to the inner value, panics if it is not yet initialized
473     #[inline(always)]
474     pub fn borrow(&self) -> &T {
475         self.get()
476     }
477 }
478
479 impl<T: Copy + Debug> Debug for LockCell<T> {
480     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
481         f.debug_struct("LockCell")
482             .field("value", &self.get())
483             .finish()
484     }
485 }
486
487 impl<T:Default> Default for LockCell<T> {
488     /// Creates a `LockCell<T>`, with the `Default` value for T.
489     #[inline]
490     fn default() -> LockCell<T> {
491         LockCell::new(Default::default())
492     }
493 }
494
495 impl<T:PartialEq + Copy> PartialEq for LockCell<T> {
496     #[inline]
497     fn eq(&self, other: &LockCell<T>) -> bool {
498         self.get() == other.get()
499     }
500 }
501
502 impl<T:Eq + Copy> Eq for LockCell<T> {}
503
504 impl<T:PartialOrd + Copy> PartialOrd for LockCell<T> {
505     #[inline]
506     fn partial_cmp(&self, other: &LockCell<T>) -> Option<Ordering> {
507         self.get().partial_cmp(&other.get())
508     }
509
510     #[inline]
511     fn lt(&self, other: &LockCell<T>) -> bool {
512         self.get() < other.get()
513     }
514
515     #[inline]
516     fn le(&self, other: &LockCell<T>) -> bool {
517         self.get() <= other.get()
518     }
519
520     #[inline]
521     fn gt(&self, other: &LockCell<T>) -> bool {
522         self.get() > other.get()
523     }
524
525     #[inline]
526     fn ge(&self, other: &LockCell<T>) -> bool {
527         self.get() >= other.get()
528     }
529 }
530
531 impl<T:Ord + Copy> Ord for LockCell<T> {
532     #[inline]
533     fn cmp(&self, other: &LockCell<T>) -> Ordering {
534         self.get().cmp(&other.get())
535     }
536 }
537
538 #[derive(Debug)]
539 pub struct Lock<T>(InnerLock<T>);
540
541 impl<T> Lock<T> {
542     #[inline(always)]
543     pub fn new(inner: T) -> Self {
544         Lock(InnerLock::new(inner))
545     }
546
547     #[inline(always)]
548     pub fn into_inner(self) -> T {
549         self.0.into_inner()
550     }
551
552     #[inline(always)]
553     pub fn get_mut(&mut self) -> &mut T {
554         self.0.get_mut()
555     }
556
557     #[cfg(parallel_queries)]
558     #[inline(always)]
559     pub fn try_lock(&self) -> Option<LockGuard<T>> {
560         self.0.try_lock()
561     }
562
563     #[cfg(not(parallel_queries))]
564     #[inline(always)]
565     pub fn try_lock(&self) -> Option<LockGuard<T>> {
566         self.0.try_borrow_mut().ok()
567     }
568
569     #[cfg(parallel_queries)]
570     #[inline(always)]
571     pub fn lock(&self) -> LockGuard<T> {
572         if ERROR_CHECKING {
573             self.0.try_lock().expect("lock was already held")
574         } else {
575             self.0.lock()
576         }
577     }
578
579     #[cfg(not(parallel_queries))]
580     #[inline(always)]
581     pub fn lock(&self) -> LockGuard<T> {
582         self.0.borrow_mut()
583     }
584
585     #[inline(always)]
586     pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
587         f(&mut *self.lock())
588     }
589
590     #[inline(always)]
591     pub fn borrow(&self) -> LockGuard<T> {
592         self.lock()
593     }
594
595     #[inline(always)]
596     pub fn borrow_mut(&self) -> LockGuard<T> {
597         self.lock()
598     }
599 }
600
601 impl<T: Default> Default for Lock<T> {
602     #[inline]
603     fn default() -> Self {
604         Lock::new(T::default())
605     }
606 }
607
608 // FIXME: Probably a bad idea
609 impl<T: Clone> Clone for Lock<T> {
610     #[inline]
611     fn clone(&self) -> Self {
612         Lock::new(self.borrow().clone())
613     }
614 }
615
616 #[derive(Debug)]
617 pub struct RwLock<T>(InnerRwLock<T>);
618
619 impl<T> RwLock<T> {
620     #[inline(always)]
621     pub fn new(inner: T) -> Self {
622         RwLock(InnerRwLock::new(inner))
623     }
624
625     #[inline(always)]
626     pub fn into_inner(self) -> T {
627         self.0.into_inner()
628     }
629
630     #[inline(always)]
631     pub fn get_mut(&mut self) -> &mut T {
632         self.0.get_mut()
633     }
634
635     #[cfg(not(parallel_queries))]
636     #[inline(always)]
637     pub fn read(&self) -> ReadGuard<T> {
638         self.0.borrow()
639     }
640
641     #[cfg(parallel_queries)]
642     #[inline(always)]
643     pub fn read(&self) -> ReadGuard<T> {
644         if ERROR_CHECKING {
645             self.0.try_read().expect("lock was already held")
646         } else {
647             self.0.read()
648         }
649     }
650
651     #[inline(always)]
652     pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
653         f(&*self.read())
654     }
655
656     #[cfg(not(parallel_queries))]
657     #[inline(always)]
658     pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
659         self.0.try_borrow_mut().map_err(|_| ())
660     }
661
662     #[cfg(parallel_queries)]
663     #[inline(always)]
664     pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
665         self.0.try_write().ok_or(())
666     }
667
668     #[cfg(not(parallel_queries))]
669     #[inline(always)]
670     pub fn write(&self) -> WriteGuard<T> {
671         self.0.borrow_mut()
672     }
673
674     #[cfg(parallel_queries)]
675     #[inline(always)]
676     pub fn write(&self) -> WriteGuard<T> {
677         if ERROR_CHECKING {
678             self.0.try_write().expect("lock was already held")
679         } else {
680             self.0.write()
681         }
682     }
683
684     #[inline(always)]
685     pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
686         f(&mut *self.write())
687     }
688
689     #[inline(always)]
690     pub fn borrow(&self) -> ReadGuard<T> {
691         self.read()
692     }
693
694     #[inline(always)]
695     pub fn borrow_mut(&self) -> WriteGuard<T> {
696         self.write()
697     }
698 }
699
700 // FIXME: Probably a bad idea
701 impl<T: Clone> Clone for RwLock<T> {
702     #[inline]
703     fn clone(&self) -> Self {
704         RwLock::new(self.borrow().clone())
705     }
706 }
707
708 /// A type which only allows its inner value to be used in one thread.
709 /// It will panic if it is used on multiple threads.
710 #[derive(Copy, Clone, Hash, Debug, Eq, PartialEq)]
711 pub struct OneThread<T> {
712     #[cfg(parallel_queries)]
713     thread: thread::ThreadId,
714     inner: T,
715 }
716
717 #[cfg(parallel_queries)]
718 unsafe impl<T> std::marker::Sync for OneThread<T> {}
719 #[cfg(parallel_queries)]
720 unsafe impl<T> std::marker::Send for OneThread<T> {}
721
722 impl<T> OneThread<T> {
723     #[inline(always)]
724     fn check(&self) {
725         #[cfg(parallel_queries)]
726         assert_eq!(thread::current().id(), self.thread);
727     }
728
729     #[inline(always)]
730     pub fn new(inner: T) -> Self {
731         OneThread {
732             #[cfg(parallel_queries)]
733             thread: thread::current().id(),
734             inner,
735         }
736     }
737
738     #[inline(always)]
739     pub fn into_inner(value: Self) -> T {
740         value.check();
741         value.inner
742     }
743 }
744
745 impl<T> Deref for OneThread<T> {
746     type Target = T;
747
748     fn deref(&self) -> &T {
749         self.check();
750         &self.inner
751     }
752 }
753
754 impl<T> DerefMut for OneThread<T> {
755     fn deref_mut(&mut self) -> &mut T {
756         self.check();
757         &mut self.inner
758     }
759 }