]> git.lizzy.rs Git - rust.git/blob - src/libstd/rt/thread.rs
9f6cf68245eab59d8f521c720c1f715012626d10
[rust.git] / src / libstd / rt / thread.rs
1 // Copyright 2013 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 use libc;
12 use ops::Drop;
13
14 #[allow(non_camel_case_types)] // runtime type
15 type raw_thread = libc::c_void;
16
17 pub struct Thread {
18     main: ~fn(),
19     raw_thread: *raw_thread,
20     joined: bool
21 }
22
23 impl Thread {
24     pub fn start(main: ~fn()) -> Thread {
25         fn substart(main: &~fn()) -> *raw_thread {
26             unsafe { rust_raw_thread_start(main) }
27         }
28         let raw = substart(&main);
29         Thread {
30             main: main,
31             raw_thread: raw,
32             joined: false
33         }
34     }
35
36     pub fn join(self) {
37         assert!(!self.joined);
38         let mut this = self;
39         unsafe { rust_raw_thread_join(this.raw_thread); }
40         this.joined = true;
41     }
42 }
43
44 impl Drop for Thread {
45     fn drop(&self) {
46         assert!(self.joined);
47         unsafe { rust_raw_thread_delete(self.raw_thread) }
48     }
49 }
50
51 extern {
52     pub fn rust_raw_thread_start(f: &(~fn())) -> *raw_thread;
53     pub fn rust_raw_thread_join(thread: *raw_thread);
54     pub fn rust_raw_thread_delete(thread: *raw_thread);
55 }