]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/thread_info.rs
add inline attributes to stage 0 methods
[rust.git] / src / libstd / sys_common / thread_info.rs
1 // Copyright 2014 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.
4 //
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.
10
11 #![allow(dead_code)] // stack_guard isn't used right now on all platforms
12
13 use cell::RefCell;
14 use thread::Thread;
15 use thread::LocalKeyState;
16
17 struct ThreadInfo {
18     stack_guard: Option<usize>,
19     thread: Thread,
20 }
21
22 thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = RefCell::new(None) }
23
24 impl ThreadInfo {
25     fn with<R, F>(f: F) -> Option<R> where F: FnOnce(&mut ThreadInfo) -> R {
26         if THREAD_INFO.state() == LocalKeyState::Destroyed {
27             return None
28         }
29
30         THREAD_INFO.with(move |c| {
31             if c.borrow().is_none() {
32                 *c.borrow_mut() = Some(ThreadInfo {
33                     stack_guard: None,
34                     thread: NewThread::new(None),
35                 })
36             }
37             Some(f(c.borrow_mut().as_mut().unwrap()))
38         })
39     }
40 }
41
42 pub fn current_thread() -> Option<Thread> {
43     ThreadInfo::with(|info| info.thread.clone())
44 }
45
46 pub fn stack_guard() -> Option<usize> {
47     ThreadInfo::with(|info| info.stack_guard).and_then(|o| o)
48 }
49
50 pub fn set(stack_guard: Option<usize>, thread: Thread) {
51     THREAD_INFO.with(|c| assert!(c.borrow().is_none()));
52     THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo{
53         stack_guard: stack_guard,
54         thread: thread,
55     }));
56 }
57
58 // a hack to get around privacy restrictions; implemented by `std::thread`
59 pub trait NewThread {
60     fn new(name: Option<String>) -> Self;
61 }