]> git.lizzy.rs Git - rust.git/blob - src/librustrt/bookkeeping.rs
auto merge of #19648 : mquandalle/rust/patch-1, r=alexcrichton
[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 #[allow(missing_copy_implementations)]
30 pub struct Token { _private: () }
31
32 impl Drop for Token {
33     fn drop(&mut self) { decrement() }
34 }
35
36 /// Increment the number of live tasks, returning a token which will decrement
37 /// the count when dropped.
38 pub fn increment() -> Token {
39     let _ = TASK_COUNT.fetch_add(1, atomic::SeqCst);
40     Token { _private: () }
41 }
42
43 pub fn decrement() {
44     unsafe {
45         if TASK_COUNT.fetch_sub(1, atomic::SeqCst) == 1 {
46             let guard = TASK_LOCK.lock();
47             guard.signal();
48         }
49     }
50 }
51
52 /// Waits for all other native tasks in the system to exit. This is only used by
53 /// the entry points of native programs
54 pub fn wait_for_other_tasks() {
55     unsafe {
56         let guard = TASK_LOCK.lock();
57         while TASK_COUNT.load(atomic::SeqCst) > 0 {
58             guard.wait();
59         }
60     }
61 }