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