6 use crate::sys::cloudabi::abi;
7 use crate::sys::time::checked_dur2intervals;
8 use crate::time::Duration;
10 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
16 // CloudABI has pthread_t as a pointer in which case we still want
17 // a thread to be Send/Sync
18 unsafe impl Send for Thread {}
19 unsafe impl Sync for Thread {}
22 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
23 pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
24 let p = Box::into_raw(box p);
25 let mut native: libc::pthread_t = mem::zeroed();
26 let mut attr: libc::pthread_attr_t = mem::zeroed();
27 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
29 let stack_size = cmp::max(stack, min_stack_size(&attr));
30 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
32 let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
33 // Note: if the thread creation fails and this assert fails, then p will
34 // be leaked. However, an alternative design could cause double-free
35 // which is clearly worse.
36 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
39 // The thread failed to start and as a result p was not consumed. Therefore, it is
40 // safe to reconstruct the box so that it gets deallocated.
41 drop(Box::from_raw(p));
42 Err(io::Error::from_raw_os_error(ret))
44 Ok(Thread { id: native })
47 extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
49 // Let's run some code.
50 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
57 let ret = unsafe { abi::thread_yield() };
58 debug_assert_eq!(ret, abi::errno::SUCCESS);
61 pub fn set_name(_name: &CStr) {
62 // CloudABI has no way to set a thread name.
65 pub fn sleep(dur: Duration) {
67 checked_dur2intervals(&dur).expect("overflow converting duration to nanoseconds");
69 let subscription = abi::subscription {
70 type_: abi::eventtype::CLOCK,
71 union: abi::subscription_union {
72 clock: abi::subscription_clock {
73 clock_id: abi::clockid::MONOTONIC,
80 let mut event = mem::MaybeUninit::<abi::event>::uninit();
81 let mut nevents = mem::MaybeUninit::<usize>::uninit();
82 let ret = abi::poll(&subscription, event.as_mut_ptr(), 1, nevents.as_mut_ptr());
83 assert_eq!(ret, abi::errno::SUCCESS);
84 let event = event.assume_init();
85 assert_eq!(event.error, abi::errno::SUCCESS);
91 let ret = libc::pthread_join(self.id, ptr::null_mut());
93 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
98 impl Drop for Thread {
100 let ret = unsafe { libc::pthread_detach(self.id) };
101 debug_assert_eq!(ret, 0);
105 #[cfg_attr(test, allow(dead_code))]
108 pub unsafe fn current() -> Option<Guard> {
111 pub unsafe fn init() -> Option<Guard> {
116 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
117 libc::PTHREAD_STACK_MIN