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