]> git.lizzy.rs Git - rust.git/blob - src/libcore/task.rs
core: Update task spawning example
[rust.git] / src / libcore / task.rs
1 /*
2 Module: task
3
4 Task management.
5
6 An executing Rust program consists of a tree of tasks, each with their own
7 stack, and sole ownership of their allocated heap data. Tasks communicate
8 with each other using ports and channels.
9
10 When a task fails, that failure will propagate to its parent (the task
11 that spawned it) and the parent will fail as well. The reverse is not
12 true: when a parent task fails its children will continue executing. When
13 the root (main) task fails, all tasks fail, and then so does the entire
14 process.
15
16 A task may remove itself from this failure propagation mechanism by
17 calling the <unsupervise> function, after which failure will only
18 result in the termination of that task.
19
20 Tasks may execute in parallel and are scheduled automatically by the runtime.
21
22 Example:
23
24 > spawn {||
25 >   log(debug, "Hello, World!");
26 > };
27
28 */
29 import cast = unsafe::reinterpret_cast;
30 import comm;
31 import ptr;
32 import c = ctypes;
33
34 export task;
35 export joinable_task;
36 export sleep;
37 export yield;
38 export task_notification;
39 export join;
40 export unsupervise;
41 export pin;
42 export unpin;
43 export task_result;
44 export tr_success;
45 export tr_failure;
46 export get_task;
47 export spawn;
48 export spawn_joinable;
49
50 #[abi = "rust-intrinsic"]
51 native mod rusti {
52     // these must run on the Rust stack so that they can swap stacks etc:
53     fn task_sleep(task: *rust_task, time_in_us: uint, &killed: bool);
54 }
55
56 type rust_closure = {
57     fnptr: c::intptr_t, envptr: c::intptr_t
58 };
59
60 #[link_name = "rustrt"]
61 #[abi = "cdecl"]
62 native mod rustrt {
63     // these can run on the C stack:
64     fn pin_task();
65     fn unpin_task();
66     fn get_task_id() -> task_id;
67     fn rust_get_task() -> *rust_task;
68
69     fn new_task() -> task_id;
70     fn drop_task(task_id: *rust_task);
71     fn get_task_pointer(id: task_id) -> *rust_task;
72
73     fn migrate_alloc(alloc: *u8, target: task_id);
74
75     fn start_task(id: task, closure: *rust_closure);
76 }
77
78 /* Section: Types */
79
80 type rust_task =
81     {id: task,
82      mutable notify_enabled: int,
83      mutable notify_chan: comm::chan<task_notification>,
84      mutable stack_ptr: *u8};
85
86 resource rust_task_ptr(task: *rust_task) { rustrt::drop_task(task); }
87
88 type task_id = int;
89
90 /*
91 Type: task
92
93 A handle to a task
94 */
95 type task = task_id;
96
97 /*
98 Function: spawn
99
100 Creates and executes a new child task
101
102 Sets up a new task with its own call stack and schedules it to be
103 executed.  Upon execution, the closure `f()` will be invoked.
104
105 Parameters:
106
107 f - A function to execute in the new task
108
109 Returns:
110
111 A handle to the new task
112 */
113 fn spawn(-f: sendfn()) -> task {
114     spawn_inner(f, none)
115 }
116
117 fn spawn_inner(-f: sendfn(),
118                notify: option<comm::chan<task_notification>>) -> task unsafe {
119     let closure: *rust_closure = unsafe::reinterpret_cast(ptr::addr_of(f));
120     #debug("spawn: closure={%x,%x}", (*closure).fnptr, (*closure).envptr);
121     let id = rustrt::new_task();
122
123     // set up notifications if they are enabled.
124     option::may(notify) {|c|
125         let task_ptr <- rust_task_ptr(rustrt::get_task_pointer(id));
126         (**task_ptr).notify_enabled = 1;
127         (**task_ptr).notify_chan = c;
128     }
129
130     rustrt::start_task(id, closure);
131     unsafe::leak(f);
132     ret id;
133 }
134
135 /*
136 Type: joinable_task
137
138 A task that sends notification upon termination
139 */
140 type joinable_task = (task, comm::port<task_notification>);
141
142 fn spawn_joinable(-f: sendfn()) -> joinable_task {
143     let notify_port = comm::port();
144     let notify_chan = comm::chan(notify_port);
145     let task = spawn_inner(f, some(notify_chan));
146     ret (task, notify_port);
147     /*
148     resource notify_rsrc(data: (comm::chan<task_notification>,
149                                 task,
150                                 @mutable task_result)) {
151         let (chan, task, tr) = data;
152         let msg = exit(task, *tr);
153         comm::send(chan, msg);
154     }
155
156     let notify_port = comm::port();
157     let notify_chan = comm::chan(notify_port);
158     let g = sendfn[copy notify_chan; move f]() {
159         let this_task = rustrt::get_task_id();
160         let result = @mutable tr_failure;
161         let _rsrc = notify_rsrc((notify_chan, this_task, result));
162         f();
163         *result = tr_success; // rsrc will fire msg when fn returns
164     };
165     let task = spawn(g);
166     ret (task, notify_port);
167     */
168 }
169
170 /*
171 Tag: task_result
172
173 Indicates the manner in which a task exited
174 */
175 tag task_result {
176     /* Variant: tr_success */
177     tr_success;
178     /* Variant: tr_failure */
179     tr_failure;
180 }
181
182 /*
183 Tag: task_notification
184
185 Message sent upon task exit to indicate normal or abnormal termination
186 */
187 tag task_notification {
188     /* Variant: exit */
189     exit(task, task_result);
190 }
191
192 /* Section: Operations */
193
194 /*
195 Type: get_task
196
197 Retreives a handle to the currently executing task
198 */
199 fn get_task() -> task { rustrt::get_task_id() }
200
201 /*
202 Function: sleep
203
204 Hints the scheduler to yield this task for a specified ammount of time.
205
206 Parameters:
207
208 time_in_us - maximum number of microseconds to yield control for
209 */
210 fn sleep(time_in_us: uint) {
211     let task = rustrt::rust_get_task();
212     let killed = false;
213     // FIXME: uncomment this when extfmt is moved to core
214     // in a snapshot.
215     // #debug("yielding for %u us", time_in_us);
216     rusti::task_sleep(task, time_in_us, killed);
217     if killed {
218         fail "killed";
219     }
220 }
221
222 /*
223 Function: yield
224
225 Yield control to the task scheduler
226
227 The scheduler may schedule another task to execute.
228 */
229 fn yield() { sleep(1u) }
230
231 /*
232 Function: join
233
234 Wait for a child task to exit
235
236 The child task must have been spawned with <spawn_joinable>, which
237 produces a notification port that the child uses to communicate its
238 exit status.
239
240 Returns:
241
242 A task_result indicating whether the task terminated normally or failed
243 */
244 fn join(task_port: joinable_task) -> task_result {
245     let (id, port) = task_port;
246     alt comm::recv::<task_notification>(port) {
247       exit(_id, res) {
248         if _id == id {
249             ret res
250         } else {
251             // FIXME: uncomment this when extfmt is moved to core
252             // in a snapshot.
253             // fail #fmt["join received id %d, expected %d", _id, id]
254             fail;
255         }
256       }
257     }
258 }
259
260 /*
261 Function: unsupervise
262
263 Detaches this task from its parent in the task tree
264
265 An unsupervised task will not propagate its failure up the task tree
266 */
267 fn unsupervise() { ret sys::unsupervise(); }
268
269 /*
270 Function: pin
271
272 Pins the current task and future child tasks to a single scheduler thread
273 */
274 fn pin() { rustrt::pin_task(); }
275
276 /*
277 Function: unpin
278
279 Unpin the current task and future child tasks
280 */
281 fn unpin() { rustrt::unpin_task(); }
282
283 // Local Variables:
284 // mode: rust;
285 // fill-column: 78;
286 // indent-tabs-mode: nil
287 // c-basic-offset: 4
288 // buffer-file-coding-system: utf-8-unix
289 // End: