]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/hermit/thread.rs
Rename ErrorKind::Unknown to Uncategorized.
[rust.git] / library / std / src / sys / hermit / thread.rs
1 #![allow(dead_code)]
2
3 use crate::ffi::CStr;
4 use crate::io;
5 use crate::mem;
6 use crate::sys::hermit::abi;
7 use crate::sys::hermit::thread_local_dtor::run_dtors;
8 use crate::time::Duration;
9
10 pub type Tid = abi::Tid;
11
12 pub struct Thread {
13     tid: Tid,
14 }
15
16 unsafe impl Send for Thread {}
17 unsafe impl Sync for Thread {}
18
19 pub const DEFAULT_MIN_STACK_SIZE: usize = 1 << 20;
20
21 impl Thread {
22     pub unsafe fn new_with_coreid(
23         stack: usize,
24         p: Box<dyn FnOnce()>,
25         core_id: isize,
26     ) -> io::Result<Thread> {
27         let p = Box::into_raw(box p);
28         let tid = abi::spawn2(
29             thread_start,
30             p as usize,
31             abi::Priority::into(abi::NORMAL_PRIO),
32             stack,
33             core_id,
34         );
35
36         return if tid == 0 {
37             // The thread failed to start and as a result p was not consumed. Therefore, it is
38             // safe to reconstruct the box so that it gets deallocated.
39             drop(Box::from_raw(p));
40             Err(io::Error::new_const(io::ErrorKind::Uncategorized, &"Unable to create thread!"))
41         } else {
42             Ok(Thread { tid: tid })
43         };
44
45         extern "C" fn thread_start(main: usize) {
46             unsafe {
47                 // Finally, let's run some code.
48                 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
49
50                 // run all destructors
51                 run_dtors();
52             }
53         }
54     }
55
56     pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
57         Thread::new_with_coreid(stack, p, -1 /* = no specific core */)
58     }
59
60     #[inline]
61     pub fn yield_now() {
62         unsafe {
63             abi::yield_now();
64         }
65     }
66
67     #[inline]
68     pub fn set_name(_name: &CStr) {
69         // nope
70     }
71
72     #[inline]
73     pub fn sleep(dur: Duration) {
74         unsafe {
75             abi::usleep(dur.as_micros() as u64);
76         }
77     }
78
79     pub fn join(self) {
80         unsafe {
81             let _ = abi::join(self.tid);
82         }
83     }
84
85     #[inline]
86     pub fn id(&self) -> Tid {
87         self.tid
88     }
89
90     #[inline]
91     pub fn into_id(self) -> Tid {
92         let id = self.tid;
93         mem::forget(self);
94         id
95     }
96 }
97
98 pub mod guard {
99     pub type Guard = !;
100     pub unsafe fn current() -> Option<Guard> {
101         None
102     }
103     pub unsafe fn init() -> Option<Guard> {
104         None
105     }
106 }