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.
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 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
36 pub unsafe fn new(stack: usize, p: Box<dyn FnBox()>) -> io::Result<Thread> {
38 let mut native: libc::pthread_t = mem::zeroed();
39 let mut attr: libc::pthread_attr_t = mem::zeroed();
40 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
42 let stack_size = cmp::max(stack, min_stack_size(&attr));
43 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
45 let ret = libc::pthread_create(&mut native, &attr, thread_start, &*p as *const _ as *mut _);
46 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
49 Err(io::Error::from_raw_os_error(ret))
51 mem::forget(p); // ownership passed to pthread_create
52 Ok(Thread { id: native })
55 extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
57 start_thread(main as *mut u8);
64 let ret = unsafe { abi::thread_yield() };
65 debug_assert_eq!(ret, abi::errno::SUCCESS);
68 pub fn set_name(_name: &CStr) {
69 // CloudABI has no way to set a thread name.
72 pub fn sleep(dur: Duration) {
74 let subscription = abi::subscription {
75 type_: abi::eventtype::CLOCK,
76 union: abi::subscription_union {
77 clock: abi::subscription_clock {
78 clock_id: abi::clockid::MONOTONIC,
79 timeout: dur2intervals(&dur),
85 let mut event: abi::event = mem::uninitialized();
86 let mut nevents: usize = mem::uninitialized();
87 let ret = abi::poll(&subscription, &mut event, 1, &mut nevents);
88 assert_eq!(ret, abi::errno::SUCCESS);
89 assert_eq!(event.error, abi::errno::SUCCESS);
95 let ret = libc::pthread_join(self.id, ptr::null_mut());
99 "failed to join thread: {}",
100 io::Error::from_raw_os_error(ret)
106 impl Drop for Thread {
108 let ret = unsafe { libc::pthread_detach(self.id) };
109 debug_assert_eq!(ret, 0);
113 #[cfg_attr(test, allow(dead_code))]
116 pub unsafe fn current() -> Option<Guard> {
119 pub unsafe fn init() -> Option<Guard> {
122 pub unsafe fn deinit() {}
125 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
126 libc::PTHREAD_STACK_MIN