]> git.proxmox.com Git - rustc.git/blob - vendor/parking_lot_core-0.6.2/src/thread_parker/generic.rs
New upstream version 1.48.0+dfsg1
[rustc.git] / vendor / parking_lot_core-0.6.2 / src / thread_parker / generic.rs
1 // Copyright 2016 Amanieu d'Antras
2 //
3 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 // http://opensource.org/licenses/MIT>, at your option. This file may not be
6 // copied, modified, or distributed except according to those terms.
7
8 //! A simple spin lock based thread parker. Used on platforms without better
9 //! parking facilities available.
10
11 use core::sync::atomic::{spin_loop_hint, AtomicBool, Ordering};
12 use std::{thread, time::Instant};
13
14 // Helper type for putting a thread to sleep until some other thread wakes it up
15 pub struct ThreadParker {
16 parked: AtomicBool,
17 }
18
19 impl super::ThreadParkerT for ThreadParker {
20 type UnparkHandle = UnparkHandle;
21
22 const IS_CHEAP_TO_CONSTRUCT: bool = true;
23
24 #[inline]
25 fn new() -> ThreadParker {
26 ThreadParker {
27 parked: AtomicBool::new(false),
28 }
29 }
30
31 #[inline]
32 unsafe fn prepare_park(&self) {
33 self.parked.store(true, Ordering::Relaxed);
34 }
35
36 #[inline]
37 unsafe fn timed_out(&self) -> bool {
38 self.parked.load(Ordering::Relaxed) != false
39 }
40
41 #[inline]
42 unsafe fn park(&self) {
43 while self.parked.load(Ordering::Acquire) != false {
44 spin_loop_hint();
45 }
46 }
47
48 #[inline]
49 unsafe fn park_until(&self, timeout: Instant) -> bool {
50 while self.parked.load(Ordering::Acquire) != false {
51 if Instant::now() >= timeout {
52 return false;
53 }
54 spin_loop_hint();
55 }
56 true
57 }
58
59 #[inline]
60 unsafe fn unpark_lock(&self) -> UnparkHandle {
61 // We don't need to lock anything, just clear the state
62 self.parked.store(false, Ordering::Release);
63 UnparkHandle(())
64 }
65 }
66
67 pub struct UnparkHandle(());
68
69 impl super::UnparkHandleT for UnparkHandle {
70 #[inline]
71 unsafe fn unpark(self) {}
72 }
73
74 #[inline]
75 pub fn thread_yield() {
76 thread::yield_now();
77 }