6 use crate::sys::cloudabi::abi;
7 use crate::sys::time::checked_dur2intervals;
8 use crate::sys_common::thread::*;
9 use crate::time::Duration;
11 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
17 // CloudABI has pthread_t as a pointer in which case we still want
18 // a thread to be Send/Sync
19 unsafe impl Send for Thread {}
20 unsafe impl Sync for Thread {}
23 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
24 pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
26 let mut native: libc::pthread_t = mem::zeroed();
27 let mut attr: libc::pthread_attr_t = mem::zeroed();
28 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
30 let stack_size = cmp::max(stack, min_stack_size(&attr));
31 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
33 let ret = libc::pthread_create(&mut native, &attr, thread_start, &*p as *const _ as *mut _);
34 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
37 Err(io::Error::from_raw_os_error(ret))
39 mem::forget(p); // ownership passed to pthread_create
40 Ok(Thread { id: native })
43 extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
45 start_thread(main as *mut u8);
52 let ret = unsafe { abi::thread_yield() };
53 debug_assert_eq!(ret, abi::errno::SUCCESS);
56 pub fn set_name(_name: &CStr) {
57 // CloudABI has no way to set a thread name.
60 pub fn sleep(dur: Duration) {
61 let timeout = checked_dur2intervals(&dur)
62 .expect("overflow converting duration to nanoseconds");
64 let subscription = abi::subscription {
65 type_: abi::eventtype::CLOCK,
66 union: abi::subscription_union {
67 clock: abi::subscription_clock {
68 clock_id: abi::clockid::MONOTONIC,
75 let mut event: abi::event = mem::uninitialized();
76 let mut nevents: usize = mem::uninitialized();
77 let ret = abi::poll(&subscription, &mut event, 1, &mut nevents);
78 assert_eq!(ret, abi::errno::SUCCESS);
79 assert_eq!(event.error, abi::errno::SUCCESS);
85 let ret = libc::pthread_join(self.id, ptr::null_mut());
89 "failed to join thread: {}",
90 io::Error::from_raw_os_error(ret)
96 impl Drop for Thread {
98 let ret = unsafe { libc::pthread_detach(self.id) };
99 debug_assert_eq!(ret, 0);
103 #[cfg_attr(test, allow(dead_code))]
106 pub unsafe fn current() -> Option<Guard> {
109 pub unsafe fn init() -> Option<Guard> {
114 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
115 libc::PTHREAD_STACK_MIN