]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/sgx/thread.rs
Merge commit 'e8dca3e87d164d2806098c462c6ce41301341f68' into sync_from_cg_gcc
[rust.git] / library / std / src / sys / sgx / thread.rs
1 #![cfg_attr(test, allow(dead_code))] // why is this necessary?
2 use super::unsupported;
3 use crate::ffi::CStr;
4 use crate::io;
5 use crate::num::NonZeroUsize;
6 use crate::time::Duration;
7
8 use super::abi::usercalls;
9
10 pub struct Thread(task_queue::JoinHandle);
11
12 pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
13
14 pub use self::task_queue::JoinNotifier;
15
16 mod task_queue {
17     use super::wait_notify;
18     use crate::sync::{Mutex, MutexGuard, Once};
19
20     pub type JoinHandle = wait_notify::Waiter;
21
22     pub struct JoinNotifier(Option<wait_notify::Notifier>);
23
24     impl Drop for JoinNotifier {
25         fn drop(&mut self) {
26             self.0.take().unwrap().notify();
27         }
28     }
29
30     pub(super) struct Task {
31         p: Box<dyn FnOnce()>,
32         done: JoinNotifier,
33     }
34
35     impl Task {
36         pub(super) fn new(p: Box<dyn FnOnce()>) -> (Task, JoinHandle) {
37             let (done, recv) = wait_notify::new();
38             let done = JoinNotifier(Some(done));
39             (Task { p, done }, recv)
40         }
41
42         pub(super) fn run(self) -> JoinNotifier {
43             (self.p)();
44             self.done
45         }
46     }
47
48     #[cfg_attr(test, linkage = "available_externally")]
49     #[export_name = "_ZN16__rust_internals3std3sys3sgx6thread15TASK_QUEUE_INITE"]
50     static TASK_QUEUE_INIT: Once = Once::new();
51     #[cfg_attr(test, linkage = "available_externally")]
52     #[export_name = "_ZN16__rust_internals3std3sys3sgx6thread10TASK_QUEUEE"]
53     static mut TASK_QUEUE: Option<Mutex<Vec<Task>>> = None;
54
55     pub(super) fn lock() -> MutexGuard<'static, Vec<Task>> {
56         unsafe {
57             TASK_QUEUE_INIT.call_once(|| TASK_QUEUE = Some(Default::default()));
58             TASK_QUEUE.as_ref().unwrap().lock().unwrap()
59         }
60     }
61 }
62
63 /// This module provides a synchronization primitive that does not use thread
64 /// local variables. This is needed for signaling that a thread has finished
65 /// execution. The signal is sent once all TLS destructors have finished at
66 /// which point no new thread locals should be created.
67 pub mod wait_notify {
68     use super::super::waitqueue::{SpinMutex, WaitQueue, WaitVariable};
69     use crate::sync::Arc;
70
71     pub struct Notifier(Arc<SpinMutex<WaitVariable<bool>>>);
72
73     impl Notifier {
74         /// Notify the waiter. The waiter is either notified right away (if
75         /// currently blocked in `Waiter::wait()`) or later when it calls the
76         /// `Waiter::wait()` method.
77         pub fn notify(self) {
78             let mut guard = self.0.lock();
79             *guard.lock_var_mut() = true;
80             let _ = WaitQueue::notify_one(guard);
81         }
82     }
83
84     pub struct Waiter(Arc<SpinMutex<WaitVariable<bool>>>);
85
86     impl Waiter {
87         /// Wait for a notification. If `Notifier::notify()` has already been
88         /// called, this will return immediately, otherwise the current thread
89         /// is blocked until notified.
90         pub fn wait(self) {
91             let guard = self.0.lock();
92             if *guard.lock_var() {
93                 return;
94             }
95             WaitQueue::wait(guard, || {});
96         }
97     }
98
99     pub fn new() -> (Notifier, Waiter) {
100         let inner = Arc::new(SpinMutex::new(WaitVariable::new(false)));
101         (Notifier(inner.clone()), Waiter(inner))
102     }
103 }
104
105 impl Thread {
106     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
107     pub unsafe fn new(_stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
108         let mut queue_lock = task_queue::lock();
109         unsafe { usercalls::launch_thread()? };
110         let (task, handle) = task_queue::Task::new(p);
111         queue_lock.push(task);
112         Ok(Thread(handle))
113     }
114
115     pub(super) fn entry() -> JoinNotifier {
116         let mut pending_tasks = task_queue::lock();
117         let task = rtunwrap!(Some, pending_tasks.pop());
118         drop(pending_tasks); // make sure to not hold the task queue lock longer than necessary
119         task.run()
120     }
121
122     pub fn yield_now() {
123         let wait_error = rtunwrap!(Err, usercalls::wait(0, usercalls::raw::WAIT_NO));
124         rtassert!(wait_error.kind() == io::ErrorKind::WouldBlock);
125     }
126
127     pub fn set_name(_name: &CStr) {
128         // FIXME: could store this pointer in TLS somewhere
129     }
130
131     pub fn sleep(dur: Duration) {
132         usercalls::wait_timeout(0, dur, || true);
133     }
134
135     pub fn join(self) {
136         self.0.wait();
137     }
138 }
139
140 pub fn available_parallelism() -> io::Result<NonZeroUsize> {
141     unsupported()
142 }
143
144 pub mod guard {
145     pub type Guard = !;
146     pub unsafe fn current() -> Option<Guard> {
147         None
148     }
149     pub unsafe fn init() -> Option<Guard> {
150         None
151     }
152 }