]> git.lizzy.rs Git - rust.git/blob - src/libcore/task.rs
5de9c8347fe03f52db50bcaecfc09ebe8d7a3b00
[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("Hello, World", fn (&&msg: str) {
25 >   log(debug, msg);
26 > });
27
28 */
29 import cast = unsafe::reinterpret_cast;
30 import comm;
31 import option::{some, none};
32 import option = option::t;
33 import ptr;
34
35 export task;
36 export joinable_task;
37 export sleep;
38 export yield;
39 export task_notification;
40 export join;
41 export unsupervise;
42 export pin;
43 export unpin;
44 export task_result;
45 export tr_success;
46 export tr_failure;
47 export get_task;
48 export spawn;
49 export spawn_notify;
50 export spawn_joinable;
51
52 #[abi = "rust-intrinsic"]
53 native mod rusti {
54     // these must run on the Rust stack so that they can swap stacks etc:
55     fn task_sleep(task: *rust_task, time_in_us: uint, &killed: bool);
56 }
57
58 #[link_name = "rustrt"]
59 #[abi = "cdecl"]
60 native mod rustrt {
61     // these can run on the C stack:
62     fn pin_task();
63     fn unpin_task();
64     fn get_task_id() -> task_id;
65     fn rust_get_task() -> *rust_task;
66
67     fn new_task() -> task_id;
68     fn drop_task(task_id: *rust_task);
69     fn get_task_pointer(id: task_id) -> *rust_task;
70
71     fn migrate_alloc(alloc: *u8, target: task_id);
72
73     fn start_task(id: task, closure: *u8);
74
75 }
76
77 /* Section: Types */
78
79 type rust_task =
80     {id: task,
81      mutable notify_enabled: int,
82      mutable notify_chan: comm::chan<task_notification>,
83      mutable stack_ptr: *u8};
84
85 resource rust_task_ptr(task: *rust_task) { rustrt::drop_task(task); }
86
87 type task_id = int;
88
89 /*
90 Type: task
91
92 A handle to a task
93 */
94 type task = task_id;
95
96 /*
97 Type: joinable_task
98
99 A task that sends notification upon termination
100 */
101 type joinable_task = (task, comm::port<task_notification>);
102
103 /*
104 Tag: task_result
105
106 Indicates the manner in which a task exited
107 */
108 tag task_result {
109     /* Variant: tr_success */
110     tr_success;
111     /* Variant: tr_failure */
112     tr_failure;
113 }
114
115 /*
116 Tag: task_notification
117
118 Message sent upon task exit to indicate normal or abnormal termination
119 */
120 tag task_notification {
121     /* Variant: exit */
122     exit(task, task_result);
123 }
124
125 /* Section: Operations */
126
127 /*
128 Type: get_task
129
130 Retreives a handle to the currently executing task
131 */
132 fn get_task() -> task { rustrt::get_task_id() }
133
134 /*
135 Function: sleep
136
137 Hints the scheduler to yield this task for a specified ammount of time.
138
139 Parameters:
140
141 time_in_us - maximum number of microseconds to yield control for
142 */
143 fn sleep(time_in_us: uint) {
144     let task = rustrt::rust_get_task();
145     let killed = false;
146     // FIXME: uncomment this when extfmt is moved to core
147     // in a snapshot.
148     // #debug("yielding for %u us", time_in_us);
149     rusti::task_sleep(task, time_in_us, killed);
150     if killed {
151         fail "killed";
152     }
153 }
154
155 /*
156 Function: yield
157
158 Yield control to the task scheduler
159
160 The scheduler may schedule another task to execute.
161 */
162 fn yield() { sleep(1u) }
163
164 /*
165 Function: join
166
167 Wait for a child task to exit
168
169 The child task must have been spawned with <spawn_joinable>, which
170 produces a notification port that the child uses to communicate its
171 exit status.
172
173 Returns:
174
175 A task_result indicating whether the task terminated normally or failed
176 */
177 fn join(task_port: joinable_task) -> task_result {
178     let (id, port) = task_port;
179     alt comm::recv::<task_notification>(port) {
180       exit(_id, res) {
181         if _id == id {
182             ret res
183         } else {
184             // FIXME: uncomment this when extfmt is moved to core
185             // in a snapshot.
186             // fail #fmt["join received id %d, expected %d", _id, id]
187             fail;
188         }
189       }
190     }
191 }
192
193 /*
194 Function: unsupervise
195
196 Detaches this task from its parent in the task tree
197
198 An unsupervised task will not propagate its failure up the task tree
199 */
200 fn unsupervise() { ret sys::unsupervise(); }
201
202 /*
203 Function: pin
204
205 Pins the current task and future child tasks to a single scheduler thread
206 */
207 fn pin() { rustrt::pin_task(); }
208
209 /*
210 Function: unpin
211
212 Unpin the current task and future child tasks
213 */
214 fn unpin() { rustrt::unpin_task(); }
215
216 /*
217 Function: spawn
218
219 Creates and executes a new child task
220
221 Sets up a new task with its own call stack and schedules it to be executed.
222 Upon execution the new task will call function `f` with the provided
223 argument `data`.
224
225 Function `f` is a bare function, meaning it may not close over any data, as do
226 shared functions (fn@) and lambda blocks. `data` must be a uniquely owned
227 type; it is moved into the new task and thus can no longer be accessed
228 locally.
229
230 Parameters:
231
232 data - A unique-type value to pass to the new task
233 f - A function to execute in the new task
234
235 Returns:
236
237 A handle to the new task
238 */
239 fn spawn<T: send>(-data: T, f: fn(T)) -> task {
240     spawn_inner(data, f, none)
241 }
242
243 /*
244 Function: spawn_notify
245
246 Create and execute a new child task, requesting notification upon its
247 termination
248
249 Immediately before termination, either on success or failure, the spawned
250 task will send a <task_notification> message on the provided channel.
251 */
252 fn spawn_notify<T: send>(-data: T, f: fn(T),
253                          notify: comm::chan<task_notification>) -> task {
254     spawn_inner(data, f, some(notify))
255 }
256
257 /*
258 Function: spawn_joinable
259
260 Create and execute a task which can later be joined with the <join> function
261
262 This is a convenience wrapper around spawn_notify which, when paired
263 with <join> can be easily used to spawn a task then wait for it to
264 complete.
265 */
266 fn spawn_joinable<T: send>(-data: T, f: fn(T)) -> joinable_task {
267     let p = comm::port::<task_notification>();
268     let id = spawn_notify(data, f, comm::chan::<task_notification>(p));
269     ret (id, p);
270 }
271
272 // FIXME: To transition from the unsafe spawn that spawns a shared closure to
273 // the safe spawn that spawns a bare function we're going to write
274 // barefunc-spawn on top of unsafe-spawn.  Sadly, bind does not work reliably
275 // enough to suite our needs (#1034, probably others yet to be discovered), so
276 // we're going to copy the bootstrap data into a unique pointer, cast it to an
277 // unsafe pointer then wrap up the bare function and the unsafe pointer in a
278 // shared closure to spawn.
279 //
280 // After the transition this should all be rewritten.
281
282 fn spawn_inner<T: send>(-data: T, f: fn(T),
283                           notify: option<comm::chan<task_notification>>)
284     -> task unsafe {
285
286     fn wrapper<T: send>(data: *u8, f: fn(T)) unsafe {
287         let data: ~T = unsafe::reinterpret_cast(data);
288         f(*data);
289     }
290
291     let data = ~data;
292     let dataptr: *u8 = unsafe::reinterpret_cast(data);
293     unsafe::leak(data);
294     let wrapped = bind wrapper(dataptr, f);
295     ret unsafe_spawn_inner(wrapped, notify);
296 }
297
298 // FIXME: This is the old spawn function that spawns a shared closure.
299 // It is a hack and needs to be rewritten.
300 fn unsafe_spawn_inner(-thunk: fn@(),
301                       notify: option<comm::chan<task_notification>>) ->
302    task unsafe {
303     let id = rustrt::new_task();
304
305     let raw_thunk: {code: uint, env: uint} = cast(thunk);
306
307     // set up the task pointer
308     let task_ptr <- rust_task_ptr(rustrt::get_task_pointer(id));
309
310     assert (ptr::null() != (**task_ptr).stack_ptr);
311
312     // copy the thunk from our stack to the new stack
313     let sp: uint = cast((**task_ptr).stack_ptr);
314     let ptrsize = sys::size_of::<*u8>();
315     let thunkfn: *mutable uint = cast(sp - ptrsize * 2u);
316     let thunkenv: *mutable uint = cast(sp - ptrsize);
317     *thunkfn = cast(raw_thunk.code);;
318     *thunkenv = cast(raw_thunk.env);;
319     // Advance the stack pointer. No need to align because
320     // the native code will do that for us
321     (**task_ptr).stack_ptr = cast(sp - ptrsize * 2u);
322
323     // set up notifications if they are enabled.
324     alt notify {
325       some(c) {
326         (**task_ptr).notify_enabled = 1;
327         (**task_ptr).notify_chan = c;
328       }
329       none { }
330     }
331
332     // give the thunk environment's allocation to the new task
333     rustrt::migrate_alloc(cast(raw_thunk.env), id);
334     rustrt::start_task(id, cast(thunkfn));
335     // don't cleanup the thunk in this task
336     unsafe::leak(thunk);
337     ret id;
338 }
339
340 // Local Variables:
341 // mode: rust;
342 // fill-column: 78;
343 // indent-tabs-mode: nil
344 // c-basic-offset: 4
345 // buffer-file-coding-system: utf-8-unix
346 // End: