]> git.lizzy.rs Git - rust.git/blob - src/librustrt/bookkeeping.rs
Add a doctest for the std::string::as_string method.
[rust.git] / src / librustrt / bookkeeping.rs
1 // Copyright 2013-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 //! Task bookkeeping
12 //!
13 //! This module keeps track of the number of running tasks so that entry points
14 //! with libnative know when it's possible to exit the program (once all tasks
15 //! have exited).
16 //!
17 //! The green counterpart for this is bookkeeping on sched pools, and it's up to
18 //! each respective runtime to make sure that they call increment() and
19 //! decrement() manually.
20
21 use core::atomic;
22 use core::ops::Drop;
23
24 use mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
25
26 static TASK_COUNT: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT;
27 static TASK_LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
28
29 pub struct Token { _private: () }
30
31 impl Drop for Token {
32     fn drop(&mut self) { decrement() }
33 }
34
35 /// Increment the number of live tasks, returning a token which will decrement
36 /// the count when dropped.
37 pub fn increment() -> Token {
38     let _ = TASK_COUNT.fetch_add(1, atomic::SeqCst);
39     Token { _private: () }
40 }
41
42 pub fn decrement() {
43     unsafe {
44         if TASK_COUNT.fetch_sub(1, atomic::SeqCst) == 1 {
45             let guard = TASK_LOCK.lock();
46             guard.signal();
47         }
48     }
49 }
50
51 /// Waits for all other native tasks in the system to exit. This is only used by
52 /// the entry points of native programs
53 pub fn wait_for_other_tasks() {
54     unsafe {
55         let guard = TASK_LOCK.lock();
56         while TASK_COUNT.load(atomic::SeqCst) > 0 {
57             guard.wait();
58         }
59     }
60 }