1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use alloc::boxed::FnBox;
18 use sys::cloudabi::abi;
19 use sys::time::dur2intervals;
20 use sys_common::thread::*;
23 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
29 // CloudABI has pthread_t as a pointer in which case we still want
30 // a thread to be Send/Sync
31 unsafe impl Send for Thread {}
32 unsafe impl Sync for Thread {}
35 pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>) -> io::Result<Thread> {
37 let mut native: libc::pthread_t = mem::zeroed();
38 let mut attr: libc::pthread_attr_t = mem::zeroed();
39 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
41 let stack_size = cmp::max(stack, min_stack_size(&attr));
42 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
44 let ret = libc::pthread_create(&mut native, &attr, thread_start, &*p as *const _ as *mut _);
45 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
48 Err(io::Error::from_raw_os_error(ret))
50 mem::forget(p); // ownership passed to pthread_create
51 Ok(Thread { id: native })
54 extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
56 start_thread(main as *mut u8);
63 let ret = unsafe { abi::thread_yield() };
64 debug_assert_eq!(ret, abi::errno::SUCCESS);
67 pub fn set_name(_name: &CStr) {
68 // CloudABI has no way to set a thread name.
71 pub fn sleep(dur: Duration) {
73 let subscription = abi::subscription {
74 type_: abi::eventtype::CLOCK,
75 union: abi::subscription_union {
76 clock: abi::subscription_clock {
77 clock_id: abi::clockid::MONOTONIC,
78 timeout: dur2intervals(&dur),
84 let mut event: abi::event = mem::uninitialized();
85 let mut nevents: usize = mem::uninitialized();
86 let ret = abi::poll(&subscription, &mut event, 1, &mut nevents);
87 assert_eq!(ret, abi::errno::SUCCESS);
88 assert_eq!(event.error, abi::errno::SUCCESS);
94 let ret = libc::pthread_join(self.id, ptr::null_mut());
98 "failed to join thread: {}",
99 io::Error::from_raw_os_error(ret)
105 impl Drop for Thread {
107 let ret = unsafe { libc::pthread_detach(self.id) };
108 debug_assert_eq!(ret, 0);
112 #[cfg_attr(test, allow(dead_code))]
115 pub unsafe fn current() -> Option<Guard> {
118 pub unsafe fn init() -> Option<Guard> {
123 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
124 libc::PTHREAD_STACK_MIN